在不知道高度的情况下在单元格内异步下载图像

Asynchronous image download inside a cell without knowing the height

我遇到了这个问题,我一直在尝试找出解决方法,但没有成功。 我有一个 table 视图,其中的单元格包含一张图像,但我仍然不知道该图像的高度是多少。我为 imageView 的高度约束创建了一个出口,我正在使用 PinRemoteImage 异步下载图像(我也可以使用 SDWebImage 但我认为它在 iOS 9 中有问题)。在块内部是我为高度约束分配新常量的地方,然后我进行布局更新。 单元格永远不会更新,我能正确看到图像的唯一方法是向下滚动然后向上滚动(当 table 视图重新绘制单元格时)

__weak typeof(UITableView*) weakTable = tableView;
__weak typeof(NSIndexPath*) index = indexPath;

[cell.commentImageView pin_setImageFromURL:[[CTImageHelper sharedInstance] resizedImageURLConverterFromStringWithPrefix:comment.image.completePath andOptions:optionsString] completion:^(PINRemoteImageManagerResult *result) {
   CommentTableViewCell *cellToUpdate = [weakTable cellForRowAtIndexPath:index];
   cellToUpdate.heightSize = [NSNumber numberWithFloat:result.image.size.height/2];
   cellToUpdate.commentImageViewHeightConstraint.constant = result.image.size.height/2;
        [cellToUpdate setNeedsLayout];
}];

这是自动设置table视图行高的代码

self.postTableView.estimatedRowHeight = 244.0;
self.postTableView.rowHeight = UITableViewAutomaticDimension;

还有一张关于单元格约束的图片:

关于我做错了什么有什么想法吗?谢谢!

您应该在调用 setNeedsLayout 之后调用 layoutIfNeeded 以实际触发布局。

layoutIfNeeded放在setNeedsLayout

之后
 [cellToUpdate setNeedsLayout];
 [cellToUpdate layoutIfNeeded];

 // and then tell the tableView to update.
 [weakTable beginUpdates];
 [weakTable endUpdates];
 // then scroll to the current indexPath
 [weakTable scrollToRowAtIndexPath:indexPath 
                 atScrollPosition:UITableViewScrollPositionNone 
                         animated:NO]; 

Update [weakTable beginUpdates];[weakTable endUpdates]; 如果一次多次调用它可能会崩溃。你需要确保它们之间没有冲突。

您也可以尝试只重新加载单元格本身。

 [cellToUpdate setNeedsLayout];
 [cellToUpdate layoutIfNeeded];
 [weakTable reloadRowsAtIndexPaths:[indexPath] withRowAnimation:UITableViewRowAnimationNone];

除了 setNeedsLayoutlayoutIfNeeded:

之外,您需要通过触发空更新来告诉表格视图其单元格的高度已更改
[tableView beginUpdates];
[tableView endUpdates];