Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically fixed width, dynamic height UILabel?

Tags:

uilabel

swift

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()
like image 585
MarksCode Avatar asked Dec 04 '25 15:12

MarksCode


1 Answers

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:

  • Be in the centre of the screen
  • Have a fixed width
  • Have a background colour
  • Expand to fit its contents vertically

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.

like image 119
Wez Avatar answered Dec 06 '25 06:12

Wez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!