【发布时间】:2014-09-24 11:12:32
【问题描述】:
我有一个自定义的UITableViewCell,我使用AFNetworking 将来自URL 的UIImageView 中的图像设置为。加载图像后,我想调整图像视图和单元格的大小以适合图像。
在我的tableView:cellForRowAtIndexPath: 我有以下代码:
FeedItem *feedItem = self.dataArray[indexPath.row];
FeedItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"FeedItemCell" forIndexPath:indexPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:feedItem.thumbnailUrl];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[cell.thumbnailImageView setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
cell.thumbnailImageView.image = image;
// first I set the height of the image view
cell.thumbnailImageHeightConstraint.constant = image.size.height;
// then I save the height in a dictionary to return it in tableView:heightForRowAtIndexPath:
[thumbnailHeights setObject:[NSNumber numberWithFloat:thumbnailHeight] forKey:[NSNumber numberWithInteger:indexPath.row]];
// now I reload the cell in order to have the new height applied
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"failed loading: %@", error);
}];
在我的tableView:heightForRowAtIndexPath: 我有这个:
NSNumber *thumbnailHeightNumber = [thumbnailHeights objectForKey:[NSNumber numberWithInteger:indexPath.row]];
if (thumbnailHeightNumber != nil) { // image size has been calculated
return thumbnailHeightNumber.floatValue;
}
return 0;
这类作品。在图像视图和单元格上都正确设置了高度。但是,有一些不可预知的行为:
- 当我滚动时,某些单元格有时会闪烁,好像正在重新加载,这很烦人。
- 有时会在行中显示错误的单元格。实际上,
tableView:cellForRowAtIndexPath:返回的单元格的内容是正确的,但它显示了来自之前一个单元格的内容。 - 有时单元格是完全空白的。同样,检查其内容似乎是正确的。
我注意到了一些可能与该问题相关的内容。我的 tableView:cellForRowAtIndexPath: 方法总是被调用两次,我相信这实际上是导致我的问题的原因。如果我删除[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 行,它只被调用一次(对于每一行)并且问题停止,但是当然单元格的高度不会更新。
另外,我不认为这个问题与单元格高度的实际变化有关。如果我为图像和单元格高度设置了固定高度,调用reloadRowsAtIndexPaths:withRowAnimation: 时仍然会得到相同的副作用。
因此,我希望有解决此问题的方法,或通过其他方式来实现我的动态单元格高度目标。
【问题讨论】:
标签: objective-c uitableview afnetworking