Sydney Loteria
Sydney Loteria

Reputation: 10441

Make UILabel Constraint to display full width

I'm struggling to implement to make my uilabel to stretch from the left side to right side (Full Width), I can do it easily in storyboard but I have a part on my app that needs to display a uilabel progmatically. Here's my code:

textLabel.backgroundColor = UIColor.grayColor()
textLabel.text = StringsLabel.NOINTERNET
textLabel.textAlignment = .Center
textLabel.font = UIFont.boldSystemFontOfSize(24.0)
textLabel.translatesAutoresizingMaskIntoConstraints = false
centerView.addSubview(textLabel)

let centreXTopLabel:NSLayoutConstraint = NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: centerView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0);
        centerView.addConstraint(centreXTopLabel)

Here's the screenshot of what i've got:

enter image description here

Upvotes: 0

Views: 1566

Answers (2)

krishnanunni
krishnanunni

Reputation: 510

Try this..

let views = ["textLabel" : textLabel]
let formatString = "|-[textLabel]-|"

 let constraints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:.AlignAllTop , metrics: nil, views: views)

NSLayoutConstraint.activateConstraints(constraints)

Upvotes: 0

tktsubota
tktsubota

Reputation: 9391

Pin it to the leading and trailing of the view at 0 points:

let leading = NSLayoutConstraint(item: textLabel, attribute: .Leading, relatedBy: .Equal, toItem: centerView, attribute: .Leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: textLabel, attribute: .Trailing, relatedBy: .Equal, toItem: centerView, attribute: .Trailing, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([leading, trailing])

Note that this will result in an ambiguous layout — you need to add a constraint that positions the label vertically.

Upvotes: 1

Related Questions