美文网首页简友广场想法
iOS 类似微信聊天消息的tableView数据展示

iOS 类似微信聊天消息的tableView数据展示

作者: 海边的遐想 | 来源:发表于2023-08-08 18:15 被阅读0次

总体构思:
1,展示cell类型聊天气泡
2,聊天消息的展示,按照时间倒序,并滑动到最新的一条
3,如果有滑动左边展示n条未读消息,如果不是在最底部,上拉获取下一页数据类似微信展示最上面一条的底部。
4,如果滑动到底部,有新消息则下面自动展示最新的
具体实现:
1,展示cell类型聊天气泡
cell的布局就不再缀叙,只描述左边和右边气泡:给layer添加切角
UIBezierPath* rounded = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, SCREEN_WIDTH - 602, 92+model.cellHeight+self.itemBgViewHeight.constant) byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerTopRight|UIRectCornerBottomRight) cornerRadii:CGSizeMake(12, 12)];
CAShapeLayer
shape = [[CAShapeLayer alloc] init];
shape.lineWidth = 1;
shape.fillColor = model.unlock == 1?UIColorFromRGB(0xEFF2FF).CGColor:UIColorFromRGB(0xEEF1F8).CGColor;
shape.strokeColor = model.unlock == 1?UIColorFromRGB(0x3D64FF).CGColor:UIColorFromRGB(0xEEF1F8).CGColor;
[shape setPath:rounded.CGPath];
[self.chatBGView.layer insertSublayer:shape atIndex:0];
2,聊天消息的展示,按照时间倒序,并滑动到最新的一条:
1)按照时间倒序,接口已经倒序,或者我们可以自己添加排序:

pragma mark -时间排序

  • (NSArray *) isSelectSortedArrayByTime:(BOOL)isTop {
    NSArray *sortArray = [self.mmmArray sortedArrayUsingComparator:^NSComparisonResult(LaboratorTagBaseModel * obj1, LaboratorTagBaseModel * obj2) {
    if(isTop){
    return obj1.isSelect>obj2.isSelect;//正序
    }else{
    return obj1.isSelect<obj2.isSelect;//倒叙
    }
    }];
    return sortArray;
    }
    2)滑动到最新的一条
    NSInteger s = [self.tableView numberOfSections]; //有多少组
    if (s<1) return; //无数据时不执行 要不会crash
    NSInteger r = [self.tableView numberOfRowsInSection:s-1]; //最后一组有多少行
    if (r<1) return;
    [self.tableView layoutIfNeeded];
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1]; //取最后一行数据
    [self.tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:YES]; //滚动到最后一行
    3,如果有滑动左边展示n条未读消息
    添加一个ilastOffSetY用来标识滑动距离,如果滑动没有在底部,接口获取的未读数就展示,如果没有到最底部,上拉刷新上一页数据,并实现上拉动画:
    if(weakSelf.dataArray.count > array.count){
    //根据当前请求的数据的个数,找到indexPath
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:array.count inSection:0];
    [weakSelf.tableView reloadData];
    [weakSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
    4,如果滑动到底部,有新消息则下面自动展示最新的
    轮询获取接口中的新数据,获取到的添加到数据数组中,并重复2操作
    [weakSelf.dataArray addObjectsFromArray:listArray];

相关文章

网友评论

    本文标题:iOS 类似微信聊天消息的tableView数据展示

    本文链接:https://www.haomeiwen.com/subject/lsznpdtx.html