为什么 NSLayoutConstraints 会被忽略?

Why are NSLayoutConstraints ignored?

我对 iOS 布局约束的机制有误解。请参阅下面列出的我放在 viewDidLoad 中的代码。

    var btn = UIButton()
    btn.setTitle("i am a button", forState: UIControlState.Normal)
    btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    btn.backgroundColor = UIColor.lightGrayColor()
    btn.sizeToFit()

    view.addSubview(btn)

    view.addConstraint(
        NSLayoutConstraint(item: view,
            attribute: NSLayoutAttribute.CenterX,
            relatedBy: NSLayoutRelation.Equal,
            toItem: btn,
            attribute: NSLayoutAttribute.CenterX,
            multiplier: 1.0,
            constant: 0.0))

    view.addConstraint(
        NSLayoutConstraint(item: view,
            attribute: NSLayoutAttribute.CenterY,
            relatedBy: NSLayoutRelation.Equal,
            toItem: btn,
            attribute: NSLayoutAttribute.CenterY,
            multiplier: 1.0,
            constant: 0.0))

看来我的意图很明确了。我想在设备屏幕中央看到一个按钮。但是我只能看到下面的图片。

我在项目的控制台中有一个输出太可怕了,我无法从中理解任何东西。

Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", " (Names: '|':UIWindow:0x7fd318551080 )>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful. 2015-04-28 23:46:04.516 ConsTest[5966:248434] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", " (Names: '|':UIWindow:0x7fd318551080 )>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

看起来这些约束被认为是矛盾的,因此完全被忽略了。我无法真正指出为什么我不能创建一个按钮并将其以编程方式放置在中心。非常感谢任何相关说明。

在您的 UIButton (btn) 上设置 translatesAutoresizingMaskIntoConstraints = false

例如

btn.translatesAutoresizingMaskIntoConstraints = false

推荐阅读:Adopting Auto Layout