I have a UILabel who's text changes. It has a background color that I want to always be the same width but for its height to change if needed to fit the text. Does anybody know how I might do this?
Here's what I've tried:
label.numberOfLines = 0
label.center = self.view.center
label.textAlignment = .center
label.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
label.sizeToFit()
You should probably do some reading on autolayout and learn how to structure your views with it, however, from what I can gather it looks like you want the label to:
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.greenColor()
label.numberOfLines = 0
label.textAlignment = .Center
label.text = "This is\nsome multiline\nlabel\nwith a background\n colour"
self.view.addSubview(label)
let width = NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
let centerX = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
let centerY = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
self.view.addConstraints([width, centerX, centerY])
The above code produces a green label using autolayout, there is a screenshot here.
Using numberOfLines = 0 makes sure that the view knows the label can expand to fit it's contents.
The layout constraints should be self explanitory if you read them, we set the width of the label to 50 then we set the center X and Y contraints to be equal to the view that we added the label to.
Is this what you are after? - If not you could update your question to include a mockup image of what you are trying to make.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With