我正在我的 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 添加布局约束的方式。如您所见,它们是为 Compact Width size Class 添加的,我在看到问题时正在使用它(iPhone4S 模拟器)。
约束已经通过 IB 添加,我正在用代码更新它们的常量。调试器清楚地显示常量实际上已更新,但不知何故图像以原始大小绘制。
最佳答案
灰色约束表示这些约束存在但未安装在您的 View 中。
引用下图:
- 选择灰色约束
- 打开属性检查器
- 在底部你可以看到
Installed
选项 - 如果未选中,则单击复选标记启用它
- 这将在您的 View 中安装选定的约束
更新:
您可以使用以下代码添加width
约束:
self.addConstraint(NSLayoutConstraint(
item: charImageView,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: 301.0))
您可以使用我的其他答案更新约束值:
关于ios - UIImageView 上的宽度和高度 NSLayoutConstraints 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592337/