【发布时间】:2015-12-08 17:00:29
【问题描述】:
我有以下代码在我的ViewController 的view 中以编程方式使用AutoLayout 约束简单地居中一个红色方块:
class ViewController: UIViewController {
let square: UIView
required init?(coder aDecoder: NSCoder) {
let squareFrame = CGRectMake(0.0, 0.0, 500.0, 500.0)
self.square = UIView(frame: squareFrame)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
self.view.addSubview(self.square)
self.square.backgroundColor = UIColor.redColor()
self.view.backgroundColor = UIColor.blueColor()
print(self.square)
setupConstraints()
print(self.square)
}
func setupConstraints() {
self.square.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal,
toItem: self.square, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant:0).active = true
NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal,
toItem: self.square, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant:0).active = true
}
}
然而,生成的屏幕只显示蓝色背景,没有红色方块的迹象...即使在 Xcode 中使用 查看调试 功能时也看不到它。
如果我注释掉setupConstraints(),它与我在初始化期间给正方形的原始帧一样“预期”。
顺便说一句,两个print 语句的输出完全相同:
<UIView: 0x7ff1c8d3f3e0; frame = (0 0; 500 500); layer = <CALayer: 0x7ff1c8d04c00>>
广场不见了怎么办?
更新:
当我按照@HaydenHolligan 在setupConstraints() 中的建议添加width 和height 约束时,问题仍然存在:
func setupConstraints() {
self.square.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal,
toItem: self.square, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant:0).active = true
NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal,
toItem: self.square, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant:0).active = true
// the following lines have no effect with respect to the issue mentioned aboove
let sizeFormat = "[square(100@100)]"
let size = NSLayoutConstraint.constraintsWithVisualFormat(sizeFormat, options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["square": self.square])
self.view.addConstraints(size)
}
【问题讨论】:
-
只是为了好玩,尝试为高度和宽度添加另外两个约束
-
感谢您的建议,但似乎无济于事......添加宽度/高度约束没有效果(至少在以我在更新问题中显示的方式添加时,你认识另一个?)@HaydenHolligan
-
[square(100@100)]没有定义 100 x 100 大小,而是 100 像素宽度和 100 优先级 -
另请注意,现在添加约束时会立即应用约束,但只有在代码屈服于运行循环时才会应用,因此立即记录大小不会显示一旦已应用约束。
-
该死,我应该回答这个问题而不是评论:p
标签: ios swift autolayout ios-autolayout