heightForRowAtIndexPath无法正常工作

时间:2016-05-28 18:20:36

标签: ios iphone swift uitableview heightforrowatindexpath

我正在尝试在tableView中显示具有正确宽高比的图像。我已经预先计算了图像的宽高比,它似乎在实际图像上正常工作,但在显示的单元格上却没有。

单元格中的图像代码:

private var cellImage: UIImage? {
        get { return cellImageView.image }
        set {
            cellImageView?.image = newValue
            if let newimage = newValue {
                heightConstraint.constant = newimage.size.width / CGFloat(aspectRatio)
            }
        }
    }

tableView中的代码:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
            return tableView.bounds.size.width / CGFloat(aspectRatio)
    }

aspectRatio是两者中相同的变量。 aspectRation =图像的宽度/高度。另外,我检查了两个地方收到的高度是否相同,它们是相同的值(在运行时)。

任何人都知道为什么没有正确设置单元格高度?

2 个答案:

答案 0 :(得分:0)

您可以使用动态单元格高度并使单元格适合其中的imageView 查看本教程 https://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift

答案 1 :(得分:0)

谢谢大家,问题得到解决。这是我找到的解决方案:

我删除了cellImage的高度约束的计算,而是将图像视图的自动布局约束添加到单元格的下边距。 这解决了这个问题。