iOS 将图像加载到 table 视图单元格中

iOS load image into table view cell

更新

现在图像在加载时显示,但仍有一个问题我无法解决。 图像与单元格的内容重叠,即使三个视图处于垂直堆栈中(第一个是图像,接下来的两个是标签视图)。 我想知道一个视图如何与堆栈视图中的其他视图重叠

现在我的 talbe 视图委托方法如下所示:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: BaseTableViewCell!
    if let contents = contents {
        let content = contents[indexPath.row]
        if let imageUrl = content.imageUrl, let url = URL(string: imageUrl) {
            cell = tableView.dequeueReusableCell(withIdentifier: "ImageContentRow", for: indexPath) as! ContentWithImageTableViewCell
            Alamofire.request(url).responseImage(completionHandler: { (response) in
                if let image = response.result.value {
                    cell.imageView?.image = image
                    cell.setNeedsLayout()
                }
            })
        }else{
            cell = tableView.dequeueReusableCell(withIdentifier: "ContentRow", for: indexPath) as! ContentTableViewCell
        }
        cell.contentTitleVeiw.text = content.title
        cell.contentLeadView.text = content.lead
    }
    return cell!
}

我对 iOS 很陌生。我已经学习了教程并观看了视频课程,现在我想实现我的第一个应用程序。 我尝试阅读提要并显示内容的标题、导语和图像(如果有的话)。 我定义了一个单元格,带有一个 UIMageVeiw 和两个 UILables,最后我将它们嵌入到一个垂直的 StackView 中(我将分布设置为 Fill)。 一切正常,但图像不会自动显示,即使我单击单元格或滚动 TableVeiw。 即使我将图像视图设置为 Aspect Fit(并将其嵌入到垂直堆栈视图的顶部),当图像显示时它会保持其原始大小并与单元格内容重叠。 我这两天想找出我做错了什么,但我无法解决。

我尝试这样显示数据:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: BaseTableViewCell!
    if let contents = contents {
        let content = contents[indexPath.row]
        if let imageUrl = content.imageUrl, let url = URL(string: imageUrl) {
            cell = tableView.dequeueReusableCell(withIdentifier: "ImageContentRow", for: indexPath) as! ContentWithImageTableViewCell
            cell.imageView?.af_setImage(withURL: url)
        }else{
            cell = tableView.dequeueReusableCell(withIdentifier: "ContentRow", for: indexPath) as! ContentTableViewCell
        }
        cell.contentTitleVeiw.text = content.title
        cell.contentLeadView.text = content.lead
    }
    return cell!
}

图像视图单元格的视图层次结构如下所示:

启动我的应用程序并显示数据后,我的列表如下所示:

在我点击一个应该显示图像的单元格或将其滚动并返回后,结果是这样的:

至少这是我的带有两个原型单元格的列表视图控制器 (一张有图,一张无图)

您需要通知 tableView 图像已加载并且必须重新绘制单元格。

尝试改变

cell.imageView?.af_setImage(withURL: url)

cell.imageView?.af_setImage(withURL: url, completion: { (_) in
    self.tableView.beginUpdates()
    self.tableView.setNeedsDisplay()
    self.tableView.endUpdates()
})

看看我的回答 - 最后你可能需要在 imageView.

上明确设置高度