Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adjust width of UILabel in Swift 3

I'm trying to get my UILabel to get wider (along with its border and background color) as the content gets more - and then less when the content is reduced.

Where do I go to get started, I've looked at the Attributes Inspectors and it looks like this can only be done with code (which I'm fine with).

I thought adding two labels in a horizontal stack would do the trick, but it doesn't update in real-time (it will update the label only on launch).

like image 803
Brewski Avatar asked Nov 26 '22 23:11

Brewski


2 Answers

Try using :

myLabel.sizeToFit()

on your label.This should update the label's frame to fit the content.

like image 162
java_doctor_101 Avatar answered Dec 05 '22 13:12

java_doctor_101


let label:UILabel = UILabel()

label.textColor=UIColor.black
label.font = UIFont(name: "Halvetica", size: 17)
label.numberOfLines = 1

label.text = "your string"
label.sizeToFit()

label.frame = CGRect(x: 5, y: imageView.frame.height+10, width: label.frame.width, height:label.frame.height)
like image 33
D.l.Prasad Avatar answered Dec 05 '22 14:12

D.l.Prasad