“视图层次结构没有为约束做准备”错误Swift 3

时间:2017-04-16 11:38:36

标签: ios swift xcode autolayout

我正在尝试添加一个按钮并以编程方式设置约束,但我一直收到此错误,无法弄清楚我的代码有什么问题。我在这里看了其他问题,但在我的案例中它们并没有太大帮助。

    btn.setTitle("mybtn", for: .normal)
    btn.setTitleColor(UIColor.blue, for: .normal)
    btn.backgroundColor = UIColor.lightGray
    view.addSubview(btn)
    btn.translatesAutoresizingMaskIntoConstraints = false

    let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0)

    let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0)

    let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)

    btn.addConstraints([left, right, top])

3 个答案:

答案 0 :(得分:9)

adding constraints到视图时,“[约束]中涉及的任何视图必须是接收视图本身或接收视图的子视图”。您正在将约束添加到btn,因此它无法理解约束所引用的view的内容,因为它既不是btn也不是btn的子视图}。如果您将约束添加到view而不是btn,则会解决该错误。

或者甚至更好,正如Khalid所说,使用activate代替,在这种情况下,您无需担心视图层次结构中添加约束的位置:

let btn = UIButton(type: .system)
btn.setTitle("mybtn", for: .normal)
btn.setTitleColor(.blue, for: .normal)
btn.backgroundColor = .lightGray
view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    btn.leftAnchor.constraint(equalTo: view.leftAnchor),
    btn.rightAnchor.constraint(equalTo: view.rightAnchor),
    btn.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)
])

答案 1 :(得分:2)

使用激活约束。在iOS 9之外,您可以使用激活

{{1}}

example project

答案 2 :(得分:0)

尝试将leftright约束添加到view而不是btn

相关问题