为什么 NSLayoutConstraints 会被忽略?

Jay*_*man 2 ios nslayoutconstraint

我遇到了对 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))
Run Code Online (Sandbox Code Playgroud)

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

iPhone 6 模拟器

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

无法同时满足约束。可能以下列表中的至少一项约束是您不想要的。试试这个: (1) 查看每个约束并尝试找出您不期望的;(2) 找到添加不需要的约束或约束的代码并修复它。(注意:如果看到 NSAutoresizingMaskLayoutConstraints 不明白,请参考 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档) ( "", "", "", " (Names: '|':UIWindow:0x7fd318551080 )>" )

将尝试通过打破约束来恢复

在 UIViewAlertForUnsatisfiableConstraints 处创建一个符号断点以在调试器中捕获它。中列出的 UIView 上的 UIConstraintBasedLayoutDebugging 类别中的方法也可能会有所帮助。2015-04-28 23:46:04.516 ConsTest[5966:248434] 无法同时满足约束。可能以下列表中的至少一项约束是您不想要的。试试这个: (1) 查看每个约束并尝试找出您不期望的;(2) 找到添加不需要的约束或约束的代码并修复它。(注意:如果你看到 NSAutoresizingMaskLayoutConstraints 不明白,请参考 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档) ( "", "", "", " (Names: '

将尝试通过打破约束来恢复

在 UIViewAlertForUnsatisfiableConstraints 处创建一个符号断点以在调试器中捕获它。中列出的 UIView 上的 UIConstraintBasedLayoutDebugging 类别中的方法也可能会有所帮助。

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

Jon*_*han 5

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

例如

btn.translatesAutoresizingMaskIntoConstraints = false
Run Code Online (Sandbox Code Playgroud)

推荐阅读:采用自动布局