Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UILabel resize to fit text

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?

like image 968
zorro2b Avatar asked Aug 31 '16 02:08

zorro2b


People also ask

How do I change the size of labels in Xcode?

You can set the Minimum Font Scale or size in Storyboard/Xib when you set it up in IB under the Attributes inspector. I prefer scale, as it is better at fitting longer text on iPhone 4/5/iPod touches. If you set the size, you can get cut off earlier than with scale.

What is UILabel?

A view that displays one or more lines of informational text.


2 Answers

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
}
like image 113
Rakshith Nandish Avatar answered Nov 08 '22 16:11

Rakshith Nandish


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 :)

like image 45
balkaran singh Avatar answered Nov 08 '22 17:11

balkaran singh