Reputation: 175
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)
Upvotes: 0
Views: 77
Reputation: 26383
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.
Upvotes: 0
Reputation: 2854
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)
Upvotes: 1