我有一个表视图,我正在其中加载图像,并通过以下函数在cellForRowAt中对图像视图设置约束:
func setImageConstraints(height: Double, width: Double) {
if (width > height) {
let ratio = self.photoView.frame.width / width
let newHeight = height * ratio
let newWidth = self.maxWidth
self.photoWidthConstraint.constant = newWidth
self.photoHeightConstraint.constant = newHeight
self.photoWidthConstraint.isActive = true
self.photoHeightConstraint.isActive = true
}
else {
let ratio = self.photoView.frame.height / height
let newHeight = self.maxHeight
let newWidth = width * ratio
self.photoWidthConstraint.constant = newWidth
self.photoHeightConstraint.constant = newHeight
self.photoWidthConstraint.isActive = true
self.photoHeightConstraint.isActive = true
}
}
问题是,当第一次加载单元格时,图像的高度/宽度不正确,直到单元格滚动出视图,然后返回视图。不过,当单元格最初加载时,我似乎不知道如何使其工作。
在tableView:willDisplayCell:forRowAtIndexPath:
方法中设置单元格的约束。
在cellForRowAtIndexPath:
方法中,尚未设置单元的框架,也尚未将单元添加到表视图中。