如何在 Swift 中以编程方式添加约束
How to add constraints programmatically in Swift
我在XCode中设置了myWebView
底部约束74
。但在某些情况下我想将它设置为等于 0
。为此我做了:
let bottomConstraint = NSLayoutConstraint(item: myWebView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: myWebView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
myWebView.addConstraint(bottomConstraint)
但它不起作用。我怎样才能让它发挥作用?
您的代码似乎告诉:"I want the center of my webview to be at 0px from the center of my web view"。
我认为情况几乎总是如此 ;)。
我想你要加的约束一定是和webview的superview的bottom相关的。
您可以进行如下操作:
let bottomConstraint = NSLayoutConstraint(item: myWebView, attribute: .Bottom, relatedBy: .Equal, toItem: myWebView.superview, attribute: .Bottom, multiplier: 1, constant: 0)
myWebView.superview.addConstraint(bottomConstraint)
请注意,我向 "positioned" 视图的父视图添加了定位约束。
我在XCode中设置了myWebView
底部约束74
。但在某些情况下我想将它设置为等于 0
。为此我做了:
let bottomConstraint = NSLayoutConstraint(item: myWebView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: myWebView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
myWebView.addConstraint(bottomConstraint)
但它不起作用。我怎样才能让它发挥作用?
您的代码似乎告诉:"I want the center of my webview to be at 0px from the center of my web view"。
我认为情况几乎总是如此 ;)。
我想你要加的约束一定是和webview的superview的bottom相关的。
您可以进行如下操作:
let bottomConstraint = NSLayoutConstraint(item: myWebView, attribute: .Bottom, relatedBy: .Equal, toItem: myWebView.superview, attribute: .Bottom, multiplier: 1, constant: 0)
myWebView.superview.addConstraint(bottomConstraint)
请注意,我向 "positioned" 视图的父视图添加了定位约束。