我正在try 在完成后滚动到UITableView的底部

我本来有

 [self.tableView reloadData]
 NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];

[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

但是我读到重载数据是异步的,所以滚动不会发生,因为self.tableView[self.tableView numberOfSections][self.tableView numberOfRowsinSection都是0.

谢谢

奇怪的是我用的是:

[self.tableView reloadData];
NSLog(@"Number of Sections %d", [self.tableView numberOfSections]);
NSLog(@"Number of Rows %d", [self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1);

在控制台中,它返回Sections=1,Row=-1;

当我在cellForRowAtIndexPath中做完全相同的NSLogs时,我得到了Sections=1和Row=8;(8是正确的)

推荐答案

重新加载在下一个布局过程中发生,这通常发生在您将控制权返回到运行循环时(例如,在您的按钮操作或任何返回操作之后).

因此,在表视图重新加载后运行某些内容的一种方法就是强制表视图立即执行布局:

[self.tableView reloadData];
[self.tableView layoutIfNeeded];
 NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection: ([self.tableView numberOfSections]-1)];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

另一种方法是使用dispatch_async:

[self.tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
     NSIndexPath* indexPath = [NSIndexPath indexPathForRow: ([self.tableView numberOfRowsInSection:([self.tableView numberOfSections]-1)]-1) inSection:([self.tableView numberOfSections]-1)];

    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
});

使现代化

经过进一步调查,我发现表视图在从reloadData返回之前向其数据源发送tableView:numberOfSections:tableView:numberOfRowsInSection:.如果委托实现了tableView:heightForRowAtIndexPath:,那么表视图也会在从reloadData返回之前发送(对于每一行).

但是,在布局阶段之前,表视图不会发送tableView:cellForRowAtIndexPath:tableView:headerViewForSection,默认情况下,当您将控制权返回到运行循环时,会发生布局阶段.

我还发现,在一个小小的测试程序中,问题中的代码会正确地滚动到表视图的底部,让我做任何特殊的事情(比如发送layoutIfNeeded或使用dispatch_async).

Objective-c相关问答推荐

Clang:将 id 之类的类型转换警告提升为 class

UICollectionView:一行或一列

如何将 CGPoint 添加到 NSMutableArray?

用 UIActivityIndi​​catorView 替换 UIBarButtonItem

在 10.9 上以编程方式启用对辅助设备的访问

NSLocale 和国家名称

将长按手势和拖动手势结合在一起

如果用户点击屏幕键盘,我如何关闭键盘?

在objective-c / cocoa-touch中是否有一个方便的功能来找到最小的数字?

如何调整 UIModalPresentationFormSheet 的大小?

NSUserDefaults 的限制是什么?

CoreData 关系故障?

判断 NSInteger 是奇数还是偶数

更改 UIBarButtonItem 的 Tint colored颜色

xcode storyboard Container View - 如何访问视图控制器

如何在Objective C(NSRegularExpression)中编写正则表达式?

UITableViewCell 右侧有图像?

如何在 UITextField 上自动打开键盘?

最大 CGFloat 值是否有常数?

Objective C 消息分发机制