在更新imageView swift 4的高度限制时,无法同时满足约束
我有一个stack view
,如下图所示:
因此,我以编程方式更改image
的高度,使其适合从我的服务器下载的图像,如果没有图像,图像的高度限制将设置为零。
这是我的代码:
let imageUrl = URL(string :imageString) if let data = try? Data(contentsOf: imageUrl!) { guard let actualImage: UIImage = UIImage(data: data) else{ print("No image!") ImageView.image = nil defaultImageHeightContrainst = ImageHeightContrainst.constant ImageHeightContrainst.constant = 0 layoutIfNeeded() return } let imageHeight = actualImage.size.height * actualImage.scale print("imageHeight = \(imageHeight)") defaultImageHeightContrainst = ImageHeightContrainst.constant ImageHeightContrainst.constant = imageHeight layoutIfNeeded() //here display the image to the imageview ImageView.kf.setImage(with: imageUrl) }
使用上面的代码,图像高度是根据从互联网下载的实际图像高度来缩放。如果没有图像,“图像”部分也已经设置为0。
这就是我的预期,但是现在每当“图像”高度变得更高以便适合实际图像高度时,我就会面临错误
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" )
在询问之前,我已经检查了所有其他约束,这些都是正确设置的。我甚至禁用所有可以改变“图像”高度的代码,一旦禁用,就没有问题。只有当我打算改变时才会出现错误高度。
我甚至尝试在layoutIfNeeded()
之前添加ImageView.translatesAutoresizingMaskIntoConstraints = false
,但错误仍然存在。
那么,为了适应从服务器下载的实际图像,更改图像高度的正确方法是什么?
考虑到最后一个约束说
""
我假设你在UITableViewCell
中使用stackView
来在tableView
实现自动高度单元格。 如果我的假设是正确的,那么问题不在于stackView
,也不在于stackView
,而在于UITableView
与UITableViewAutomaticDimension
和Autolayout一起工作的方式。 如果布局按预期工作,并且警告是唯一让您烦恼的事情,请阅读以下内容。
因此在我看来,这是一个已知的“bug”的结果 – tableView
设置的高度与autolayout计算的高度发生碰撞。 在渲染单元格时, tableView
首先应用默认高度,计算自动布局高度,然后使用后者 – 至少看起来如此。 看我的问题 。 上面提到的约束( 'UIView-Encapsulated-Layout-Height'
)是UITableView
应用的约束,后来消失了。
这意味着您使用的约束可能没问题。 只需将其中一个约束定义为priority = 999
(这样直到它停用默认高度约束它不会导致任何冲突)。 最后,无论如何都会导致使用约束,因此不会导致任何布局问题。
例如,如果您将stackView
限制为适合单元格的contentView
,请将stackView.bottomAnchor
设置为contentView.bottomAnchor
,优先级设置为999.如果您以编程方式执行布局,这可能是您的解决方案:
let bottomConstraint = tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) bottomConstraint.priority = UILayoutPriority(rawValue: 999) NSLayoutConstraint.activate([ // rest of the constraints stackView.topAnchor.constraint(equalTo: contentView.topAnchor), stackView.leftAnchor.constraint(equalTo: contentView.leftAnchor), stackView.rightAnchor.constraint(equalTo: contentView.rightAnchor), bottomConstraint, ])
如果在故事板中进行布局,只需在故事板中选择适当的约束,并在属性检查器中将其优先级设置为999(例如):