我试图从代码创建用户界面。这是代码:
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)
}
根据我以下的书籍教程,此代码应创建一个Button和一个Label。当我运行模拟器时,没有任何显示(空白模拟器)。你能帮我找到错误吗?
答案 0 :(得分: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)
试图将它们放在另一个之上。
这两个限制中的一个必须要去!