UILabel dynamic height with Autolayout

Adding a UILabel to UIScrollView and with a couple of lines of code you would be able to achieve the dynamic height.

But, there is one more way and thats without writing a single line of code.

So, lets get started on it.

Approach 1:

Mistakes that we would make is explained below. (UILabel and UIScrollView)
Add a UIScrollView , set top, left, bottom, right margin set to 0 against superview as per your requirement.

Add the UILabel and we do the same for UILabel (top,left,bottom,right margin set to 0 with respect to SuperView, which is UIScrollView )

With this approach scrollview would not get idea on the scroll limits. It will set the content size, where it would scroll horizontally.

You can still go with this approach. Explained in conclusion.

Approach 2:
Now, lets go with the correct way to Code . 
It includes the following hierarchy UIView -> UIScrollView -> UILabel.

Step 1 : Add the UIView , set the margin according. Here I am using some margin with respect to the superview.




Step2: Add UIScrollView and set the margin with respect to superview with a constant 0. 
Simple, Yeah!




Step 3:  The final components in UILabel , so add and set the margin with respect to superview with a constant 0. Do we get the required output? Yes or no. Answer is NO 😕

Output is shown below.



The reason behind that is , the UIScrollView calculate content size based on the content of UILabel. It pins to the top , left and bottom and expands right.

To solve this issue, UIScrollView must be informed about the width. i.e some way to tell UIScrollView to change to width based on some width. Oh ya, some width.

Let's get back to the hierarchy now. Its UIView -> UIScrollView -> UILabel.

We will make the width of UILabel equals the width of UIView by adding the following constraint. For that select UIView and UILabel and set it to equals width as shown in the image below.



And finally we get the expected output with auto scroll.




So, now change the orientation to Landscape mode, width of UIView change and so does the UILabel width.


Conclusion:
1) Use the UIView -> UIScrollView -> UILabel hierarchy 
2) Set the width of UILabel to UIView.

Note:  You can also use the Approach 1, provided you set the UILabel widths equal to UIScrollView's superView, which is UIView (UIView of the UIViewController)


Comments

Popular posts from this blog

hitTest on iOS to identify the view being hit

CMTimeMakeWithSeconds explained

Custom Editing Control for UITableViewCell , like iPhone Mail Appliation