【问题标题】:Asynchronous image download inside a cell without knowing the height在不知道高度的情况下在单元格内异步下载图像
【发布时间】:2016-01-26 16:21:06
【问题描述】:

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

__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];
}];

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

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

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

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

【问题讨论】:

  • 不要对 imageview 进行高度限制。下载图像时更新此单元格。细胞应该会自动生长

标签: ios objective-c uitableview autolayout objective-c-blocks


【解决方案1】:

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]; 

更新 [weakTable beginUpdates];[weakTable endUpdates]; 如果一次调用不止一次,可能会崩溃。你需要确保它们之间没有碰撞。

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

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

【讨论】:

  • 我添加了它仍然没有刷新它:/
  • 如何自行更改单元格高度? heightSize 是做什么的?或者你如何使用它?
  • heightSize 是保持最终图像高度的属性
  • 那么如何更改单元格高度?还是动态计算的?
  • @JoanCardona 那么如何更改单元格高度?还是动态计算的?
【解决方案2】:

您应该在调用setNeedsLayout 之后调用layoutIfNeeded 才能真正触发布局。

【讨论】:

    【解决方案3】:

    除了setNeedsLayoutlayoutIfNeeded 之外,您需要通过触发空更新来告诉表格视图其单元格的高度已更改:

    [tableView beginUpdates];
    [tableView endUpdates];
    

    【讨论】:

    • tableview 的行为非常奇怪,然后崩溃。有什么想法吗?
    • 越界:[__NSArrayM objectAtIndex:]:空数组的索引 12 越界。它只会发生这种情况,当我没有这些行时,数组看起来不错
    • 您能否修改您的问题以包含您使用/设置该数组的相关部分?你在主线程上调用表格视图吗?
    猜你喜欢
    • 2019-03-25
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2016-03-02
    相关资源
    最近更新 更多