UITableView
。tableView 从有时较慢的服务器加载大图像。我为每个图像启动一个 URLConnection,并重新加载与连接对象保存的 URLConnection 相应的 indexPath。连接本身在 tableView 上调用 -reloadData
。现在,当点击“加载更多”按钮时,我会滚动到新数据集的第一行,位置在底部。这很好地解决了我的异步加载系统。
但我遇到了以下问题:当连接“太快”时,tableView 在仍然滚动到新数据集的第一行时就在给定的 indexPath 重新加载数据,tableView 会向后滚动该单元格高度的一半。
这是它应该看起来的样子和实际上的样子:
![what it should look like](https://istack.dev59.com/hRPsC.gif)
![what it actually looks like](https://istack.dev59.com/3JnlC.gif)
[[self tableView] beginUpdates];
for (NSMutableDictionary *post in object) {
[_dataSource addObject:post];
[[self tableView] insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[_dataSource indexOfObject:post] inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
}
[[self tableView] endUpdates];
[[self tableView] scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_dataSource indexOfObject:[object firstObject]] inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
-tableView:cellForRowAtIndexPath:
方法会在数据源数组中的对象为字符串时启动JWURLConnection,并在完成块中用UIImage
实例替换它。然后重新加载给定的单元格:
id image = [post objectForKey:@"thumbnail_image"];
if ([image isKindOfClass:[NSString class]]) {
JWURLConnection *connection = [JWURLConnection connectionWithGETRequestToURL:[NSURL URLWithString:image] delegate:nil startImmediately:NO];
[connection setFinished:^(NSData *data, NSStringEncoding encoding) {
[post setObject:[UIImage imageWithData:data] forKey:@"thumbnail_image"];
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}];
[cell startLoading];
[connection start];
}
else if ([image isKindOfClass:[UIImage class]]) {
[cell stopLoading];
[cell setImage:image];
}
else {
[cell setImage:nil];
}
我能否在tableView滚动完成之前防止执行-reloadRowsAtIndexPaths:withRowAnimation:
调用?或者你能想象一种好的方法来防止这种行为吗?