如何以编程方式添加NSLayoutConstraint

3

我想将一个按钮作为根视图的子视图添加。该按钮必须水平和垂直居中于父视图。我正在使用编程方法NSLayoutConstraints。以下是我的代码。

class ViewController: UIViewController {

    var button: UIButton!

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
        button = UIButton()
        button.setTitle("Hello World", forState: .Normal)
        button.backgroundColor = UIColor.blueColor()
        button.sizeToFit()
        self.view.addSubview(button)
        NSLayoutConstraint.activateConstraints([
            NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0),
            NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
        ])
    }
}

我收到了以下警告信息,同时我也没有得到预期的结果。
2016-07-20 11:01:10.187 build[26982:309535] 无法同时满足约束条件。很可能以下列表中的某个约束条件不是您所需的。 请尝试以下操作: 1.查看每个约束条件并尝试确定哪些条件不符合您的预期; 2.找到添加了不需要的约束条件的代码并进行修复。(注意:如果您看到了NSAutoresizingMaskLayoutConstraints,而您又不知道它是什么,请参阅UIView属性“translatesAutoresizingMaskIntoConstraints”的文档。)(“”,“”,“(名称:' | ':UIViewControllerWrapperView:0x7faa4be31770)>”,“”) 将尝试通过打破约束来恢复
请在UIViewAlertForUnsatisfiableConstraints处设置符号断点以在调试器中捕获此错误。UIConstraintBasedLayoutDebugging类别中的方法可能也会有所帮助。 2016-07-20 11:01:10.188 build[26982:309535] 无法同时满足约束条件。很可能以下列表中的某个约束条件不是您所需的。 请尝试以下操作: 1.查看每个约束条件并尝试确定哪些条件不符合您的预期; 2.找到添加了不需要的约束条件的代码并进行修复。(注意:如果您看到了NSAutoresizingMaskLayoutConstraints,而您又不知道它是什么,请参阅UIView属性“translatesAutoresizingMaskIntoConstraints”的文档。)(“”,“”,“”,“(名称:' | ':UIViewControllerWrapperView:0x7faa4be31770)>”) 将尝试通过打破约束来恢复
请在UIViewAlertForUnsatisfiableConstraints处设置符号断点以在调试器中捕获此错误。UIConstraintBasedLayoutDebugging类别中的方法可能也会有所帮助。
1个回答

10

NSLayoutConstraint 是一种动态添加自动布局约束的方式之一。

let new_view:UIView! = UIView(frame: CGRectMake(20, 20, 100, 100));
new_view.backgroundColor = UIColor.redColor();
new_view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(new_view);
NSLayoutConstraint(item: new_view,
        attribute: .Leading,
        relatedBy: .Equal,
        toItem: view,
        attribute: .LeadingMargin,
        multiplier: 1.0,
        constant: 0.0).active = true
NSLayoutConstraint(item: new_view,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: view,
        attribute: .TopMargin,
        multiplier: 1.0,
        constant: 20.0).active = true
NSLayoutConstraint(item: new_view,
        attribute: .Height,
        relatedBy: .Equal,
        toItem: new_view,
        attribute:.Width,
        multiplier: 2.0,
        constant:0.0).active = true
NSLayoutConstraint(item: new_view,
        attribute: .Width,
        relatedBy: .Equal,
        toItem: nil,
        attribute: .NotAnAttribute,
        multiplier: 1.0,
        constant: 100.0).active = true

translatesAutoresizingMaskIntoConstraints设置为false并调用layoutIfNeeded方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接