【发布时间】:2015-09-29 16:49:32
【问题描述】:
当我在 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 中删除图像并设置背景颜色进行测试,那么约束会按预期工作,这样我就可以看到发生了什么。
有人知道为什么会这样吗?
【问题讨论】:
标签: ios uiview uiimageview nslayoutconstraint