[英]UIImageView creates extra width/height constraints
当我在Xcode中调试视图时,我的UIImageView
具有以下自动布局约束:
我期望在视图的设置器上将其宽度和高度初始化为6。 在调试时,这些约束应该是40而不是6。但是由于某种原因,(内容大小)的宽度和高度还有额外的约束,实际上是设置为40。
这是我imageView
的didSet
的方法IBOutlet
:
@IBOutlet private weak var imageView: UIImageView! {
didSet {
if let widthConstraint = imageView.constraintForLayoutAttribute(.Width)
{
widthConstraint.constant = MinimumImageLength
imageView.layoutIfNeeded()
}
else
{
let widthConstraint = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: MinimumImageLength)
NSLayoutConstraint.activateConstraints([widthConstraint])
}
if let heightConstraint = imageView.constraintForLayoutAttribute(.Height)
{
heightConstraint.constant = MinimumImageLength
imageView.layoutIfNeeded()
}
else
{
let heightConstraint = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: MinimumImageLength)
NSLayoutConstraint.activateConstraints([heightConstraint])
}
}
}
如果存在,则将获得宽度和高度约束,并设置其最小宽度。 注意,在我看来,我已经明确设置了这些宽度和高度约束,因此我的代码从不输入宽度和高度的else
。
为了获得正确的约束,我使用以下函数:
extension UIView
{
func constraintForLayoutAttribute(layoutAttribute: NSLayoutAttribute) -> NSLayoutConstraint?
{
let filteredArray = constraints.filter { $0.firstAttribute == layoutAttribute }
return filteredArray.first
}
}
稍后,我使用相同的函数获取宽度/高度并更改两个常量。 更新宽度/高度约束后,我调用layoutIfNeeded()
。 (我也尝试过通过不幸运地调用setNeedsUpdateConstraints()
进行调试)。
有趣的是,如果我通过从UIImageView
删除图像并仅设置背景颜色进行测试,约束就会按预期工作,从而可以看到正在发生的事情。
有谁知道为什么会这样?
在仔细检查我的函数constraintForLayoutAttribute:
,filteredArray属性实际上由几个约束组成。 我期望的宽度限制和其他两个内容大小限制。
我不确定是否有改进方法的“解决方案”,但我只是决定为宽度和高度约束创建出口,并改用这些出口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.