如果我从情节提要添加视图,我可以通过代码处理它们的自动布局约束,但如果我在通过代码添加的视图上尝试此操作,则无法处理。
我在 viewDidLoad() 中调用下面的代码但不起作用,缺少什么部分?
var testView = UIView()
testView.backgroundColor = UIColor.greenColor()
self.view.addSubview(testView)
let views : [String : AnyObject] = ["testView": testView]
var allConstraints = [NSLayoutConstraint]()
let verticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[testView(100)]",
options: [],
metrics: nil,
views: views)
allConstraints += verticalConstraint
let horizontalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[testView(200)]",
options: [],
metrics: nil,
views: views)
allConstraints += horizontalConstraint
NSLayoutConstraint.activateConstraints(allConstraints)
ps:也尝试了这些行但没有帮助
self.view.addConstraints(verticalConstraint)
self.view.addConstraints(horizontalConstraint)