IBOutlets的约束冲突

时间:2016-03-09 22:15:25

标签: ios nslayoutconstraint

当我尝试手动设置NSLayoutConstraint的约束时,我遇到IBOutlet冲突。从本质上讲,我只是在故事板中放置视图,以便大致了解它们的外观,然后创建IBOutlet来引用它们。但是所有约束都添加在代码中:

class LoginViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var view1: UIView!
    @IBOutlet weak var view2: UView2!
    @IBOutlet weak var name: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()


        view2.addSubview(name)

        //add constraints
        NSLayoutConstraint(item: view1, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0).active = true
        NSLayoutConstraint(item: view1, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: -self.view.frame.height * 0.07).active = true
        NSLayoutConstraint(item: view1, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.8, constant: 0).active = true
        NSLayoutConstraint(item: view1, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.4, constant: 0).active = true

        NSLayoutConstraint(item: view2, attribute: .Width, relatedBy: .Equal, toItem: view1, attribute: .Width, multiplier: 1, constant: 0).active = true
        NSLayoutConstraint(item: view2, attribute: .CenterX, relatedBy: .Equal, toItem: view1, attribute: .CenterX, multiplier: 1, constant: 0).active = true
        NSLayoutConstraint(item: view2, attribute: .Top, relatedBy: .Equal, toItem: view1, attribute: .Bottom, multiplier: 1, constant: self.view.frame.height * 0.01).active = true
        NSLayoutConstraint(item: view2, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.1, constant: 0).active = true



      }
 }

当我在代码中创建视图时,NSLayoutConstraint冲突消失了,即var view2 = UIView()或我注释view2的约束。我不明白。

编辑:根据日志,虽然在故事板中没有设置自动布局约束,但NSIBPrototypingLayoutConstraint的问题似乎是UIView-Encapsulated-Layout-Height'view2。我现在感到困惑的是为什么view1没有这个问题,因为它们都被添加到了故事板中?

1 个答案:

答案 0 :(得分:1)

您还没有在故事板中设置view2的约束,因此Xcode正在为您秘密添加约束。您需要做的是在故事板中添加view2的约束,并且(因为您在运行时并不真正想要它们)告诉Xcode在构建时删除这些约束:

"Remove at build time" checkbox in the Size inspector