【问题标题】:UITableViewCell with UIImageView - Incorrect width at first load带有 UIImageView 的 UITableViewCell - 首次加载时宽度不正确
【发布时间】:2020-07-14 16:41:45
【问题描述】:

我有一个 UITableView,其中的单元格包含 自定义层,例如 阴影、画线角半径。我已经通过 Storyboard 使用 iPhone SE 视图大小的 Autolayout 完成了设计。

问题是当第一次初始化 UITableView 时它显示如下(不应该这样):

但是,当滚动到底部时,它会显示为应有的样子,如下所示:

我做了很多事情来更新它,例如:

cell?.imageView.invalidateIntrinsicContentSize()
cell?.imageView.setNeedsUpdateConstraints()
cell?.imageView.setNeedsLayout()
cell?.imageView.layoutIfNeeded()
cell?.imageView.setNeedsDisplay()
cell?.imageView.translatesAutoresizingMaskIntoConstraints = false

但它不起作用。

那么,有什么想法可以让它在第一个显示加载后作为第二张图片?

- 更新-

这里是对应tableView的cellForRow

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell: GProjectsFTContentTVCell = tableView.dequeueReusableCell(withIdentifier: "GProjFTContentHeaderCellID") as! GProjectsFTContentTVCell

        cell.performPopulateData(data: self.contentInfo![indexPath.row])

        tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.automatic)

        return cell
    }

及其细胞类别:

func performPopulateData(data: APIJSON.ProjectList)
{
   let urlFriendlyFileName: String? = data.cover?.replacingOccurrences(of: " ", with: "%20")
        self.vwGPFTCTVCBannerPanel.layer.cornerRadius = 20
        self.vwGPFTCTVCBannerPanel.dropShadow()
        self.ivGPFTCTVCBannerImage.roundCorners(corners: [.topLeft, .topRight], radius: 20.0)

        AF.request(urlFriendlyFileName ?? "").responseImage(completionHandler: { response in

            if let image = response.value {
                self.ivGPFTCTVCBannerImage.image = image

            }
        })

        self.lblGPFTCTVCTitle.text = data.title
        self.lblGPFTCTVCTitle.font = FontPredefine.SFProSemiBold(withSize: 16.0)
        self.lblGPFTCTVCTitle.textColor = ColorPredefine.greenTextColor
        self.lblGPFTCTVCSubTitle.text = data.subtitle
        self.lblGPFTCTVCSubTitle.font = FontPredefine.SFProRegular(withSize: 12.0)

}

对于布局,我做的是这样的:

【问题讨论】:

  • 请在cellForRow分享您的完整代码。
  • 我很想知道 imageView 的约束是什么样的。另外,您的 imageViews 的 contentMode 是什么?最后,你所有的图片大小都一样吗?
  • @koen 看看更新的问题
  • @rob 看看我编辑过的视觉效果。我使用的内容模式是AspectFill
  • @Rob 是的!我想我错过了一件重要的事情,将其加载到主线程中!

标签: ios swift uitableview uiimageview


【解决方案1】:

宾果!我花了几个小时来解决这个问题,我很傻,因为我错过了这个重要的事情,我只需要输入这个代码:

DispatchQueue.main.async {
    cell?.performPopulateData(data: self.contentInfo![indexPath.row])
}

现在它可以正常工作了。感谢@Rob 给了我这个想法。

【讨论】:

  • 这可能解决了您的图像问题,但仍然不建议从cellForRow 内下载数据。您的数据应该准备就绪,然后您可以更新您的表格。
  • @koen 我承认应该首先缓存图像。但就我而言,我想通过先显示文本然后最后显示图像来减少数据加载时间。否则,我需要在加载其他数据之前等待图像完成他们的工作,并且需要用户等待。
猜你喜欢
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多