user12747957
user12747957

Reputation:

How to configure dynamic height for UILabel in swift 5?

I am trying to setup UILabel in view controller with dynamic height so that it fits according to the text.

I tried various examples available on stack overflow but to no good yet.

is there any other specific method for Swift 5 to make UILabel height dynamic?

UI Constraints

View Controller

Upvotes: 0

Views: 3846

Answers (5)

Madhubala
Madhubala

Reputation: 56

Specify numberOfLines = 0 and in label height constraints specify like greater than or equal to zero.

Upvotes: 0

Janbaz Ali
Janbaz Ali

Reputation: 206

In your UIConstraints I can see height constraint = 134, remove height constraint to dynamically adjust the height of your label.

Pragmatically you can achieve this by code below

let myLabel = UILabel()
        self.view.addSubview(myLabel)
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([myLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100),
        myLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 30),
        myLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -30)])
        myLabel.numberOfLines = 0
        myLabel.backgroundColor = .yellow
        myLabel.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "

Upvotes: 1

Pranay
Pranay

Reputation: 486

1) set the top/leading/trailing constraints of the label to superview/Safe Area. 2) set the numberOfLines = 0 in the attribute inspector for the label in the storyboard.

Upvotes: 2

Munzareen Atique
Munzareen Atique

Reputation: 478

Just remove the HeightConstraint of label from storyboard and add 0 in number of lines your label will get the text and set as per content.

Upvotes: 1

Keshu R.
Keshu R.

Reputation: 5223

Give your UILabel, leading, trailing and top constraints. Don't give bottom constraints. If you have to give bottom constraints, don't give top constraint.

Also, set numberOfLines = 0

class ViewController: UIViewController {

    @IBOutlet weak var yourLabel : UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        yourLabel.numberOfLines = 0
        // Do any additional setup after loading the view.
    }
}

Upvotes: 0

Related Questions