我正在尝试在 tableview 中制作动态图像高度。我使用 SDWebImage 从 URL 下载图像。但它不适用于几个初始单元格
下面是我写的方法
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let shareDetailCell = tableView.dequeueReusableCell(withIdentifier: THShareDetailTableViewCell.className, for: indexPath) as! THShareDetailTableViewCell
shareDetailCell.selectionStyle = UITableViewCellSelectionStyle.none
shareDetailCell.likeButton.tag = indexPath.row
//to set image dynamic height
shareDetailCell.selectionStyle.socialPostImage.sd_setImage(with: URL(string: socialInteraction[indexpath.row].largeImageUrl), placeholderImage: nil, options: .retryFailed) { (image, error, imageCacheType, imageUrl) in
if image != nil {
let imgHeight = (image?.size.height)!
shareDetailCell.heightConstraintSocialImage.constant = (imgHeight * (self.socialPostImage.frame.size.width/imgHeight))
}else {
print("image not found")
}
}
return shareDetailCell
}
最佳答案
从您的代码工作中我发现了两件事,
切勿从
estimatedHeightForRowAt
返回UITableViewAutomaticDimension
,因为估计高度永远不会是自动的,否则 x 代码无法理解它应该返回的高度。有时它会起作用,但不被视为一种好的做法。您在
cellForRowAt
方法中获取图像,这意味着在您获取图像之前,单元格的高度已经设置。因此,您的单元格图像只有那个高度。UITableViewAutomaticDimension
在系统通过heightForRowAt
方法知道该单元格的高度时起作用,而不是在那之后。
Suggestion for your problem.
获取数据后重新加载 tableView
,以便根据图像高度调整单元格高度。您也可以在分页中执行此操作。
关于ios - tableview 中的动态图像高度不适用于最初的几个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229529/