Thursday, April 21, 2016

Get Dynamic Label Size iOS


Sometimes we need to set the height or width of the text container (It could be a label, aletview or textbox) dynamically. That means it's size is depending on the text which we wanted to write/show in it.

Normally what we do is, we set the size of the text container  first, then we put or adjust  the text in it. But in this case we will measure the size of that large text, that means we are going to find out the height and width of the paragraph we want show in the text container, then we will use that height and width.

The concept is very simple. We just need to create a rectangle with the text. Then we will use the size (width/ height) of that rectangle to set the size of the text container.

In Image 1, I create a rectangle with the large text (testString) and a maximum size (constraint). Another important variable I have used which is font style (font) of the text where I have used font style name and it's size. We got the rectangle with the text. Next steps are very easy. You just have to use the width and height of this rectangle. But just remember to set the same font style which you have used for the rectangle to label or Attribute String. Otherwise the design will be broken.

Image 1: Creating a rectangle with the text
In Image 2, I set the string in the text property of a label. You can see I have changed the font style of the label as I mentioned above.

Image 2: Showing the text in a label
And in Image 3 I have changed the font style  of the NSMutableAttributedString so I did not set the font style of the label.



In image 4 you can see the output. In this image the height and width of these two labels are changing with their contents.

Image 4: Output
You can download the full project from this link.

No comments:

Post a Comment