iOS直播聊天评论区的实现

效果参照下面截图,来自映客直播APP

效果示例

先分析一下需求,新评论是从下往上顶的,那我们收到新评论把它添加到tableView的最后一行。但这样的话,如果tableView所有的cell高度加起来还不满一个tableView的高度,cell是从上往下填满的。如下图所示

常规实现效果示例

我们需要的是下图这样,从一开始就从下往上顶。

想要的效果示例

调整思路,我们可以把tableView倒过来(上下翻转180°),每次插入数据都插在第0行。这样就实现了每次插入数据,都是从下往上顶。

_tableView.transform = CGAffineTransformMakeScale(1, -1);

倒转tableView 数据插入在第0位

但这样,所有cell的内容也是倒着的,那么再把contentView再倒转一次,就正过来了。示例代码如下

在自定义cell中:

self.contentView.transform = CGAffineTransformMakeScale(1, -1);

插入的代码:

[self.modelArr insertObject:model atIndex:0];

NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];

这样就实现了。

效果图

最终效果

若想实现花椒那种用户滑到最顶部的时候,再有新消息都不在往上滚动了。则在insert的时候加个判断,判断是否到达tableView的底部(因为我们tableView翻转过,所以用户看到的顶部其实是tableView的底部),判断方法参考我的简书 如何判断tableView滑动到了底部 。如果你知道,可以跳过继续往下。

效果图:

花椒直播间评论区效果

首先你需要在tableView的底部加一个tableView的高度。

_tableView.contentInset = UIEdgeInsetsMake(0, 0, tableViewHeight, 0);

if (isReachBottom)  //如果滑动到达tableView底部

{

NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];

indexPath = [NSIndexPath indexPathForRow:self.commentDisplayedArr.count - 1 inSection:0];

//无动画,滚动到最后一个cell

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionNone animated:NO];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容