Krish
Krish

Reputation: 4232

How to change UILabel width based on text length in iOS Using Auto-Layouts

I want to display two UILabel's, however UILabel's having variable text length's According to textsize UIlabel's width need to increase using auto-layouts.

For this I wrote below auto-layouts for both UIlabel's

First Label:

1)leading Space 
2)Top space
3)Width
4)height
5)Horizontal spacing

Second Label:

1)Trailing space
2)Top space
3)Width
4)height

how can we do this ?

Please help me.

my code:

textLabel1.numberOfLines = 0
        textLabel1 .sizeToFit()
        textLabel1.text = "asdfdsfdghjgjhkhkjlhjkhjk"

textLabel2.numberOfLines = 0
        textLabel2 .sizeToFit()
        textLabel2.text = "asdfdsfdghjgjhkhkjlhjkhjk"

Upvotes: 2

Views: 2719

Answers (2)

Iyyappan Ravi
Iyyappan Ravi

Reputation: 3245

Select the First UILabel, set Leading, Top, bottom and set fixed width, then go to size Inspector -> select fixed width constraints -> Relation -> select Greater than or equal, example is give below,

enter image description here

enter image description here

select the Second UILabel, set Leading, Bottom, fixed width, then above same processs to be perform,

hope its helpful

Upvotes: 5

Mahendra
Mahendra

Reputation: 8924

Fist you need to set UILabel's property numberOfLines to zero and set text wrapping to word wrap. And after that give the required constraint.

If you are not getting desired result then you need to calculate the label's dynamic height by boundingRectWithSize:... method and give height constraint accordingly.

Upvotes: 0

Related Questions