NSLayoutConstraint不起作用

时间:2014-08-27 14:50:12

标签: swift nslayoutconstraint

我想将2个按钮移动到屏幕宽度的中心。 它应该看起来像:|&lt ;-(100)FirstButton(50) - > SecondButton(100) - > |

我从第一个按钮开始。

var const = NSLayoutConstraint(item: firstButton, 
    attribute: NSLayoutAttribute.Left, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: view.superview, 
    attribute: NSLayoutAttribute.Left, 
    multiplier: 1.0, 
    constant: 100)

为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

似乎firstButton未将属性translatesAutoresizingMaskIntoConstraints设置为false

Apple translatesAutoresizingMaskIntoConstraints的文档说明:

/* By default, the autoresizing mask on a view gives rise to constraints that fully determine the view's position. This allows the auto layout system to track the frames of views whose layout is controlled manually (through -setFrame:, for example). When you elect to position the view using auto layout by adding your own constraints, you must set this property to NO. IB will do this for you. */ @available(iOS 6.0, *) open var translatesAutoresizingMaskIntoConstraints: Bool // Default YES

因此,当您添加自己的约束时,必须将firstButton' s translatesAutoresizingMaskIntoConstraints设置为false