Mostafa
Mostafa

Reputation: 1612

iOS Dynamic label width according to number of Chars

I want to Achieve this in the simplest way "Preferably using Storyboard"

I want the Gender Label to be always next to the label

I want the Gender Image to be always next to the Pet Type label, to achieve this, the label width must be dynamic according to the number of characters. I searched & found several solutions that would require tens lines of lines of code which I believe that there must be simpler solutions.

Please keep in mind that I am using constrains & I did try label.sizeToFit() and it didnt work

Thank you

Upvotes: 2

Views: 874

Answers (2)

NotABot
NotABot

Reputation: 526

User constraints. Give horizontal spacing constraint between label and gender image and animal image. Give width constraint to all the images. That should work.

Upvotes: 0

Ievgen Leichenko
Ievgen Leichenko

Reputation: 1317

That can be done with no code at all.

You've said, you are using constraints, right?

First, you have the image view pinned (presumably, centered vertically and, let's say, 16 to the left (using 'leading' constraint)).

Next, you pin your label (pet label, e.g. "Pitbull") to the image view. That would be its 'leading' constraint. Or you can left-align it with the name label. That makes no difference.

Then, you pin your gender image likewise to the pet label.

Done. When you change the text in the label, everything is recalculated automatically. (Just don't add 'width' constraint to your pet label, and it will adjust depending on the width of the text.)

Upvotes: 2

Related Questions