首页 > 解决方案 > 在 UITableView 中插入最后一行并平滑滚动

问题描述

我正在尝试创建一个类似应用程序的聊天机器人,我使用了UITableView自定义单元格来满足我的需求。每当添加新消息时,我都会创建并插入一个新行,然后滚动到UITableView. 一切正常,直到某个点,但是当单元格的高度发生变化时(我有两种不同类型的单元格),动画很混乱,它不能平滑滚动到最后并且整个UITableView闪烁,这不是一个好用户体验。我尝试了几种方法:

1 - 将数据添加到数据源数组并重新加载UITableView,然后滚动到底部。

2 - 使用insertRowsAtIndexPaths然后滚动到底部。

他们都有滚动的相同问题。我已经习惯scrollToRowAtIndexPathUITableView

我已经上传了一个演示应用程序的代码,它代表在这里模拟相同的问题,所以它很容易理解。是该问题的视频。非常感谢任何帮助。

此问题可能不会发生在模拟器上,请在设备上运行演示项目。

在阅读了所有评论并在聊天中进行讨论后,我注意到这发生在 iPhone 5C (10.3.3) 上。我在 iPhone 5S (11.3) 上运行了演示,没有出现问题。不确定这是否与操作系统有关。

标签: iosobjective-cuitableviewuiscrollview

解决方案


Reloading whole tableview results in messy scrolling instead insert row at last position.

Make following changes in your Action Methods

- (IBAction)btnLargeCellClicked:(id)sender {    // To add large green colored row.

    /************ This is the FIRST approach. ***********/
    [arrHeight addObject:@"100"];
    [arrData addObject:@"1"];
    NSIndexPath* ip = [NSIndexPath indexPathForRow:[_myTable numberOfRowsInSection:0] inSection:0];
    [_myTable insertRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationFade];
    [self scrollTableviewToLastRow];


    /************ This is the SECOND approach. ***********/
//    [arrHeight addObject:@"100"];
//    [_myTable beginUpdates];
//    NSIndexPath *row1 = [NSIndexPath indexPathForRow:arrData.count inSection:0];
//    [arrData insertObject:@"1" atIndex:arrData.count];
//    [_myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1, nil] withRowAnimation:UITableViewRowAnimationFade];
//    [_myTable endUpdates];
//    [self scrollTableviewToLastRow];
}

And

- (IBAction)btnClicked:(id)sender {     // To add small red colored row.
    /************ This is the FIRST approach. ***********/
    [arrHeight addObject:@"50"];
    [arrData addObject:@"1"];
    NSIndexPath* ip = [NSIndexPath indexPathForRow:[_myTable numberOfRowsInSection:0] inSection:0];
    [_myTable insertRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationFade];
    [self scrollTableviewToLastRow];


    /************ This is the SECOND approach. ***********/
//    [arrHeight addObject:@"50"];
//    [_myTable beginUpdates];
//    NSIndexPath *row1 = [NSIndexPath indexPathForRow:arrData.count inSection:0];
//    [arrData insertObject:@"1" atIndex:arrData.count];
//    [_myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1, nil] withRowAnimation:UITableViewRowAnimationFade];
//    [_myTable endUpdates];
//    [self scrollTableviewToLastRow];

}

Hope this helps :)


推荐阅读