简体   繁体   English

如何以编程方式进行此自动布局?

[英]How do I programmatically make this auto layout?

How do I make the label auto layout for all devices. 如何使所有设备的标签自动布局。

        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)
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)

After you added the label as a subview you need to avoid autolayout to convert autoresizing masks into constraints or you will probably have conflicts. 在将标签添加为子视图之后,您需要避免自动布局以将自动调整大小的蒙版转换为约束,否则可能会发生冲突。

golabel.setTranslatesAutoresizingMaskIntoConstraints(false)

Here you add the constraints 在这里添加约束

 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)

Since you are not adding constraints that inhibit the label to grow the label will use its intrinsic content size, thus it can grow indefinitely based on the length and font of the text. 由于未添加限制标签增长的约束,因此标签将使用其固有的内容大小,因此可以根据文本的长度和字体无限期地增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM