ios - 在 UITableView 中插入最后一行并平滑滚动
问题描述
我正在尝试创建一个类似应用程序的聊天机器人,我使用了UITableView
自定义单元格来满足我的需求。每当添加新消息时,我都会创建并插入一个新行,然后滚动到UITableView
. 一切正常,直到某个点,但是当单元格的高度发生变化时(我有两种不同类型的单元格),动画很混乱,它不能平滑滚动到最后并且整个UITableView
闪烁,这不是一个好用户体验。我尝试了几种方法:
1 - 将数据添加到数据源数组并重新加载UITableView
,然后滚动到底部。
2 - 使用insertRowsAtIndexPaths
然后滚动到底部。
他们都有滚动的相同问题。我已经习惯scrollToRowAtIndexPath
了UITableView
我已经上传了一个演示应用程序的代码,它代表在这里模拟相同的问题,所以它很容易理解。这是该问题的视频。非常感谢任何帮助。
此问题可能不会发生在模拟器上,请在设备上运行演示项目。
在阅读了所有评论并在聊天中进行讨论后,我注意到这发生在 iPhone 5C (10.3.3) 上。我在 iPhone 5S (11.3) 上运行了演示,没有出现问题。不确定这是否与操作系统有关。
解决方案
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 :)
推荐阅读
- python - 使用 python,我需要每天使用 MongoDB api 将文档从 Azure CosmosDB 传输到 Postrgres,可能使用 Azure 函数
- javascript - 跟随光标位置将图像添加到 DOM
- python - 在通过 gerrit-python-api 包采摘樱桃时确定其是合并冲突还是相同的树?
- excel - Excel Power Query 合并和转换列
- python - 根据另一个数组的元素从 numpy 数组中删除元素
- javascript - 指定replicationRegions时的Javascript NestedStack CREATE_FAILED
- react-native - UI Kitten 中的 Top Navigation 组件如何在 React Native Stack Navigator 中用作自定义标题
- python - 字典更新序列元素#0的长度为0;2 是必需的
- java - 缺少工件 org.springframework.boot:spring-boot-starter-data-jpa:jar:2.4.5Java(0)
- sql - T-SQL 从表中删除交叉对