-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)
}
根據本書教程,我遵循,這段代碼應該創建一個按鈕和一個標籤。當我運行模擬器時什麼也沒有顯示(空白模擬器)。你能幫我找到錯誤嗎?
當您運行該代碼時,控制檯中會出現一個巨大的錯誤消息,從「無法同時滿足約束...」開始。它完全解釋了這個問題。閱讀!它告訴你到底是什麼錯誤。不要忽略控制檯消息。 – matt 2015-04-02 14:48:11