【发布时间】:2019-09-04 20:33:47
【问题描述】:
我有一个UITableView,配置非常基本。 tableview 单元格只包含一个UIImageView。
查看层次结构:
我想在UIImageView 中呈现不同尺寸的图像。 UIImageView 的宽度需要固定为可变高度。
Auto Layout 应该可以自动调整单元格的大小,但是在异步下载图像时不起作用。
这是我的cellForRowAt indexPath。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell
let item = array[indexPath.row]
let url = URL.init(string: item["imageUrl"] as! String)!
cell.myImage.image = nil
DispatchQueue.global().async {
let data = try! Data.init(contentsOf: url)
DispatchQueue.main.async {
let image = UIImage.init(data: data)!
if let cell = tableView.cellForRow(at: indexPath) as? Cell, cell.myImage.image == nil {
let multiplier = cell.myImage.bounds.width / image.size.width
cell.heightConstraint.constant = multiplier * image.size.height
cell.myImage.image = image
cell.layoutIfNeeded()
}
}
}
return cell
}
我在 GitHub 上有一个示例项目设置来演示该问题。 https://github.com/RishabhTayal/AutoTableViewPOC
【问题讨论】:
标签: ios swift uitableview autolayout