以编程方式添加前导约束会导致应用崩溃

时间:2017-02-10 10:35:38

标签: ios nslayoutconstraint

我试图了解如何以编程方式添加约束。到目前为止,我的代码是这样的:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //addViewStandard()
        addConstraintsView()
    }

    func addConstraintsView() {
        let someView = UIView(frame: CGRect.zero)
        someView.backgroundColor = UIColor.blue
        // I want to mimic a frame set of CGRect(x: 20, y: 50, width: 50, height: 50)
        let widthConstraint = NSLayoutConstraint(item: someView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
        let heightConstraint = NSLayoutConstraint(item: someView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
        let leadingConstraint = NSLayoutConstraint(item: someView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20)
        someView.translatesAutoresizingMaskIntoConstraints = false
        someView.addConstraints([widthConstraint, heightConstraint, leadingConstraint])
        view.addSubview(someView)
    }
}

现在,当我运行应用程序时,它会因为主要约束而崩溃。错误消息是“#34;无法设置布局,其视图层次结构没有为约束"做好准备。我在这做错了什么?我应该向对象添加约束(在这种情况下为蓝色框)还是将它们添加到超级视图中?

编辑:

代码更改后,我有:

func addConstraintsView() {
        let someView = UIView(frame: CGRect.zero)
        someView.backgroundColor = UIColor.blue
        view.addSubview(someView)
        someView.translatesAutoresizingMaskIntoConstraints = false
        let widthConstraint = NSLayoutConstraint(item: someView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
        let heightConstraint = NSLayoutConstraint(item: someView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
        let leadingConstraint = NSLayoutConstraint(item: someView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: 20)
        someView.addConstraints([widthConstraint, heightConstraint])
        view.addConstraints([leadingConstraint])
    }

1 个答案:

答案 0 :(得分:3)

首先,

view.addSubview(someView)
someView.translatesAutoresizingMaskIntoConstraints = false

应该在约束阶段之前;您必须在将someView添加到其超级视图后应用约束。

此外,如果您的目标是iOS 9,我建议您使用

等布局锚点
let widthConstraint = someView.widthAnchor.constraint(equalToConstant: 50.0)
let heightConstraint = someView.heightAnchor.constraint(equalToConstant: 50.0)
let leadingConstraint = someView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0)
NSLayoutConstraint.activate([widthConstraint, heightConstraint, leadingConstraint])

这样您就不必担心将约束应用于哪个视图。

最后(并澄清您的疑问),如果您不能使用布局锚点,则应将前导约束添加到超级视图,而不是视图。