使用代码而非故事板添加的视图的自动布局 (VFL)
Autolayout (VFL) for View that is added with code not storyboard
如果我从情节提要中添加视图,我可以通过代码处理它们的自动布局约束,但如果我在通过代码添加的视图上尝试此操作,则无法处理。
我在我的 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)
您需要关闭自动调整掩码到约束的转换。默认情况下,它设置为 true
,如果您倾向于忘记这一点,它会添加您不打算添加的约束。
您可以通过
将其设置为 false
var myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
translatesAutoresizingMaskIntoConstraints
If this property’s value is YES, the system creates a set of
constraints that duplicate the behavior specified by the view’s
autoresizing mask. By default, the property is set to YES for any view
you programmatically create. If you add views in Interface Builder,
the system automatically sets this property to NO.
如果我从情节提要中添加视图,我可以通过代码处理它们的自动布局约束,但如果我在通过代码添加的视图上尝试此操作,则无法处理。
我在我的 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)
您需要关闭自动调整掩码到约束的转换。默认情况下,它设置为 true
,如果您倾向于忘记这一点,它会添加您不打算添加的约束。
您可以通过
将其设置为 falsevar myView = UIView()
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
translatesAutoresizingMaskIntoConstraints
If this property’s value is YES, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. By default, the property is set to YES for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to NO.