2016-03-09 147 views
0

當我嘗試手動設置我的IBOutlet的約束時,我遇到了NSLayoutConstraint衝突。從本質上講,我只是在故事板上放置觀點,以獲得他們如何看待的一般意義,然後創建IBOutlet來引用它們。但是,所有的約束都在代碼中添加:IBOutlets約束衝突

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的約束。我不明白。

編輯:基於日誌,對於view2,問題似乎爲NSIBPrototypingLayoutConstraintUIView-Encapsulated-Layout-Height',但在故事板中沒有設置自動佈局約束。我現在困惑的是爲什麼不view1有這個問題,因爲他們都添加在故事板?

+0

你有沒有刪除所有來自SB的限制? – sschale

+0

是的。我重複檢查 – Liumx31

回答

1

您還沒有在故事板中的view2上設置約束,所以Xcode爲您祕密添加約束。你需要做的是在故事板添加約束view2,以及(因爲你真的不希望他們在運行時)告訴Xcode中在構建時,以消除那些限制:

"Remove at build time" checkbox in the Size inspector

+0

我創建了一個虛擬約束,並選擇了該選項,它工作!謝謝,雖然如果我可能會問你另一個問題 - 我試着在代碼'view2.removeConstraints(view2.constraints)'中做它,但這是有效的,「構建時刪除」和那行代碼之間有什麼區別'viewDidLoad中()'? – Liumx31

+0

另外我沒有這樣做'view1',但它的作品? – Liumx31

+2

@ user245954 - 「構建時刪除」的選擇只是一種更有效的方法,可以防止在運行時創建約束,然後再刪除/停用約束。此外,請注意並非所有視圖的約束都在「view2.constraints」集合中,而是可能附加到最近的共同父級(例如超級視圖)。通過選擇「在構建時刪除」,您擺脫了弄清楚哪些約束在哪裏的愚蠢行爲。 (坦率地說,如果我要以編程方式刪除/激活/更改它們,我會建立一個IB出口集合並使用它。) – Rob