[英]How do I create constraints programmatically in Swift?
I am trying to set up the width of a UIButton
using this code:我正在尝试使用以下代码设置
UIButton
的宽度:
constraintButtonPlayWidth = NSLayoutConstraint(item: buttonPlay,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Width,
multiplier: 1,
constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
But the button gets stretched too much;但是按钮被拉得太长了; probably because
toItem: self.view
.可能是因为
toItem: self.view
。 I tried modifying the constant of the constraint, but that didn't change anything.我尝试修改约束的常量,但这并没有改变任何东西。
How do I set up correctly this constraint so it actually has a width of 100?如何正确设置此约束,使其实际宽度为 100?
You were close.你很接近。 The constraint only should have a single item since it is not relative to another item.
约束应该只有一个项目,因为它与另一个项目无关。
constraintButtonPlayWidth = NSLayoutConstraint (item: buttonPlay,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.