我在View Controller的updateViewConstraints()
内的UIImgeView实例上设置.Width和.Top NSLayoutConstraints。在XCode可视化调试器中,我可以看到实际设置了约束,但由于某种原因它们没有被使用(?)它们看起来不是(内容大小)并且是灰色的。
当我使用NSLog输出约束时我也可以看到它们被设置,但不知何故图像保持原始大小......
这是什么意思?
constraints in parent: [<NSLayoutConstraint:0x7b379590 UIImageView:0x7af897b0.centerX == UIView:0x7b37d2e0.centerX>,
<NSLayoutConstraint:0x7b36e3d0 V:|-(0)-[UIImageView:0x7af897b0] (Names: '|':UIView:0x7b37d2e0 )>]
constraints in view: [<NSContentSizeLayoutConstraint:0x7ae892b0 H:[UIImageView:0x7af897b0(301)] Hug:251 CompressionResistance:750>,
<NSContentSizeLayoutConstraint:0x7ae834e0 V:[UIImageView:0x7af897b0(365)] Hug:251 CompressionResistance:750>]
设置约束的代码:
/// Image view with the character + ellipse
@IBOutlet weak var charImageView: UIImageView!
override func updateViewConstraints() {
super.updateViewConstraints()
charImageView.widthLayoutConstraint?.constant = 301.0
charImageView.heightLayoutConstraint?.constant = 365.0
}
我用来获取widthLayoutConstraint
和heightLayoutConstraint
extension UIView{
/**
Gets the width layout constraint defined as the NSLayoutConstraint whose first item is self and first attribute is Height
*/
var heightLayoutConstraint:NSLayoutConstraint? {
get{
for constraint in constraints {
if constraint.firstItem as? UIView == self &&
constraint.firstAttribute == NSLayoutAttribute.Height
{
return constraint
}
}
return nil
}
}
/**
Gets the width layout constraint defined as the NSLayoutConstraint whose first item is self and first attribute is Width
*/
var widthLayoutConstraint:NSLayoutConstraint? {
get{
for constraint in constraints {
if constraint.firstItem as? UIView == self &&
constraint.firstAttribute == NSLayoutAttribute.Width
{
return constraint
}
}
return nil
}
}
}
这是最初使用IB添加布局约束的方式。如您所见,它们是为紧凑宽度大小类添加的,我在看到问题时使用它(iPhone4S模拟器)。
已经通过IB添加了约束,我正在用代码更新它们的常量。调试器清楚地显示常量IS IN FACT UPDATED但不知何故图像以原始大小绘制。
答案 0 :(得分:5)
灰色约束表明这些约束存在但未在视图中安装。
参考下图:
Installed
选项<强>更新强>
您可以使用以下代码添加width
约束:
self.addConstraint(NSLayoutConstraint(
item: charImageView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 301.0))
您可以使用我的其他答案更新约束值: