首页 文章

更新图像高度约束后更新tableview单元格高度

提问于
浏览
1

我有像这样的tableview单元格 .

enter image description here

我更新了图像高度约束并重新加载 . 我在iOS 10上使用自动调整大小单元并进行测试 .

How to animate UITableViewCell height using auto-layout?

imageHeightConstraint.constant = 200 //example only. it will be dynamic. Some image height will be 200, 400, etc
self.contentView.layoutIfNeeded()
UIView.setAnimationsEnabled(false)
self.delegate?.getTableView!().beginUpdates()
self.delegate?.getTableView!().endUpdates()
UIView.setAnimationsEnabled(true)

我试图只重新加载一行而且不行 .

self.contentView.layoutIfNeeded()
let indexPath = IndexPath(item: self.tag, section: 0)
self.delegate?.getTableView!().beginUpdates()
self.delegate?.getTableView!().reloadRows(at: [indexPath], with: .none)
self.delegate?.getTableView!().endUpdates()

问题是它根本不会改变高度,除非我像这样重新加载表 .

imageHeightConstraint.constant = 200
self.delegate?.getTableView!().reloadData()

但是我不想调用reloadData,因为它会重新加载所有可见的单元和资源密集型(当用户快速滚动时也会出现滞后) . 如何正确更新图像约束并正确更新表格视图单元格(自动调整大小)?

编辑 - 使用内在大小

我删除了我的高度约束,只是在UIImageview中使用了内在大小的属性 . 然后高度是正确的但宽度太大(因为它是固有的) . 我该怎么办?

enter image description here

1 回答

  • 0

    ImageViews具有内在大小 . 这意味着他们根据图像内容获取大小 . 除非您在图像上应用宽度和高度约束,否则imageView应该能够根据图像大小调整自身大小 .

    您可以使用tableView的height属性

    self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 100
    

    现在选择您的单元格并设置前导,尾随,顶部和底部约束 . 确保不要手动设置高度/宽高比约束 .

    enter image description here

    现在,如果您只是将图像加载到imageView,单元格将根据图像的大小自动获取大小 .

    Edit:

    如果要加载的图像具有特定的大小范围,则此方法有效 . 如果要缩小图像或将高度约束设置为图像并在下载图像后更新其高度,则无需重新加载整个tableView,而是可以在tableView中重新加载特定单元格

    self.tableView.reloadRows(at: [yourIndexPath], with: .none)
    

    在这种情况下,请确保您实施

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    }
    

    EDIT:

    将imageView内容模式设置为 AspectFitScaleTofillScaleTofill

相关问题