如何为所有设备制作标签自动布局。
golabel = UILabel(frame: CGRectMake(30, 100, 350, 100))
golabel.text = "Game Over"
golabel.textColor = UIColor.whiteColor()
golabel.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 70)
self.view.addSubview(golabel)
答案 0 :(得分:1)
let golabel = UILabel()
golabel.setTranslatesAutoresizingMaskIntoConstraints(false)
let horizontalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 30)
view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 100)
view.addConstraint(verticalConstraint)
let widthConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 350)
golabel.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
golabel.addConstraint(heightConstraint)
答案 1 :(得分:0)
将标签添加为子视图后,您需要避免自动布局将自动调整蒙版转换为约束,否则您可能会发生冲突。
golabel.setTranslatesAutoresizingMaskIntoConstraints(false)
在这里添加约束
let horizontalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
self.view.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.view.addConstraint(verticalConstraint)
由于您没有添加禁止标签增长的约束,标签将使用其内在内容大小,因此它可以根据文本的长度和字体无限增长。