效果參照下面截圖,來自映客直播APP
先分析一下需求,新評論是從下往上頂的,那我們收到新評論把它添加到tableView的最后一行。但這樣的話,如果tableView所有的cell高度加起來還不滿一個tableView的高度,cell是從上往下填滿的。如下圖所示
我們需要的是下圖這樣,從一開始就從下往上頂。
調整思路,我們可以把tableView倒過來(上下翻轉180°),每次插入數據都插在第0行。這樣就實現了每次插入數據,都是從下往上頂。
_tableView.transform = CGAffineTransformMakeScale(1, -1);
但這樣,所有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];
}