2015-04-02 69 views
-1

我正在嘗試從代碼創建用戶界面。這是代碼:從代碼創建的用戶界面不會顯示

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let superview = self.view 

     let myLabel = UILabel() 
     myLabel.setTranslatesAutoresizingMaskIntoConstraints(false) 
     myLabel.text = "My Label" 

     let myButton = UIButton() 
     myButton.setTitle("My Button", forState: UIControlState.Normal) 
     myButton.backgroundColor = UIColor.blueColor() 
     myButton.setTranslatesAutoresizingMaskIntoConstraints(false) 
     superview.addSubview(myLabel) 
     superview.addSubview(myButton) 

     var myConstraint=NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0) 
     superview.addConstraint(myConstraint) 

     myConstraint=NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: myButton, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) 
     superview.addConstraint(myConstraint) 

     myConstraint=NSLayoutConstraint(item: myButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: myLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: -10) 
     superview.addConstraint(myConstraint) 

     myConstraint=NSLayoutConstraint(item: myButton, attribute: NSLayoutAttribute.Baseline, relatedBy: NSLayoutRelation.Equal, toItem: myLabel, attribute: NSLayoutAttribute.Baseline, multiplier: 1.0, constant: 0) 
     superview.addConstraint(myConstraint) 

    } 

根據本書教程,我遵循,這段代碼應該創建一個按鈕和一個標籤。當我運行模擬器時什麼也沒有顯示(空白模擬器)。你能幫我找到錯誤嗎?

+1

當您運行該代碼時,控制檯中會出現一個巨大的錯誤消息,從「無法同時滿足約束...」開始。它完全解釋了這個問題。閱讀!它告訴你到底是什麼錯誤。不要忽略控制檯消息。 – matt 2015-04-02 14:48:11

回答

1

你的第三個約束

myConstraint=NSLayoutConstraint(item: myButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: myLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: -10) 

試圖通過邊把標籤和按鈕的一面。

你的第二個約束

myConstraint=NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: myButton, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) 

試圖把它們一個在另一個之上。

這兩個限制之一將不得不去!