How to make UILabel resize to fit text

12,124

Solution 1

enter image description here

see this scrrenshot

1 first select your label width constraint

2 set the relation Greater than or equal

3 set the default constant value here i set it 10

when you change the label text it change the size of label according to its text. hope it's help :)

Solution 2

Iam guessing the label is not getting height and width, consider giving those constraints and then when your text changes use this method to determine the height and width:

    func labelSizeWithString(text: String, maxWidth : CGFloat,numberOfLines : Int) -> CGRect{
    let label = UILabel(frame: CGRectMake(0, 0, maxWidth, CGFloat.max))
    label.numberOfLines = numberOfLines
    label.text = text

    label.sizeToFit()

    return label.frame
}
Share:
12,124

Related videos on Youtube

zorro2b
Author by

zorro2b

Updated on October 17, 2022

Comments

  • zorro2b
    zorro2b over 1 year

    I have a UILabel that I have layed out in a storyboard centred in the view. It has some initial text "tap to login".

    I am changing the value of the label to be the user's name once they have logged in. Once I do this, the label is no longer centered as the UILabel has not changed size.

    How can I do this with autolayout in interface builder?

  • Josh
    Josh about 7 years
    an additional point for anyone looking at this. Make sure you haven't set both leading & trailing constraints as those override 'greater than' constraints