ios - tableview 中的动态图像高度不适用于最初的几个单元格

标签 ios swift uitableview

我正在尝试在 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
            }

最佳答案

从您的代码工作中我发现了两件事,

  1. 切勿从 estimatedHeightForRowAt 返回 UITableViewAutomaticDimension,因为估计高度永远不会是自动的,否则 x 代码无法理解它应该返回的高度。有时它会起作用,但不被视为一种好的做法。

  2. 您在 cellForRowAt 方法中获取图像,这意味着在您获取图像之前,单元格的高度已经设置。因此,您的单元格图像只有那个高度。UITableViewAutomaticDimension 在系统通过 heightForRowAt 方法知道该单元格的高度时起作用,而不是在那之后。

Suggestion for your problem.

获取数据后重新加载 tableView,以便根据图像高度调整单元格高度。您也可以在分页中执行此操作。

关于ios - tableview 中的动态图像高度不适用于最初的几个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229529/

相关文章:

ios - Collection View :numberOfItemsInSection: in UITableviewcell (DetailedCell)

ios - 更改导航后退按钮的目的地

swift - 将 float 截断到小数点后两位的最简单方法?

ios - 以 swift 编程方式在 UI 选项卡栏中 Google map

ios - 基类实现tableView时如何使用UITableViewAutomaticDimension :heightForRowAtIndexPath:

ios - 如何防止 UITableViewCell 中的手势干扰 UITableView 的滚动?

objective-c - 如何枚举 CGPoints 的 nsmutablearray?

iOS 10 barTintColor 动画

ios - swift 2 尝试/捕捉

objective-c - 具有多个部分的 UITableView 中的总行数