Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating contentSize for UIScrollView when using Auto Layout

Tags:

Here is a quick question about something which works, but could be written much better. I have a UIScrollView and a list of objects laid out inside, one under the other. Everything is done during viewDidLoad() and the placement of the objects uses Auto Layout. Here is what I do to set the contentSize height of the UIScrollView to its appropriate value.

override func viewDidAppear(animated: Bool) {     super.viewDidAppear(animated)     globalView.contentSize = CGSize(width: globalView.frame.width,                                     height: globalView.frame.height * 1.59) } 

It works, but the arbitrary value 1.59 has obviously been decided by me trying a few possible values. What is the proper way to compute the contentSize in such a case? I am doing everything programmatically. Searching the net didn't lead me to any simple and clear answer, so eventhough it may be a somewhat duplicate question I decided to reformulate it.

like image 275
Michel Avatar asked Aug 15 '16 03:08

Michel


Video Answer


1 Answers

Giving content size programatically is not good way. The below solution which will work using autolayout, dont need to set content size at all. It will calculate as per how many UI fields added to view.

Step 1 :

Add Scrollview to view in storyboard and add leading, trailing, top and bottom constraints (All values are zero).

Step 2 :

Don't add directly views which you need on directly scrollview, First add one view to scrollview (that will be our content view for all UI elements). Add below constraints to this view.

1) Leading, trailing, top and bottom constraints (All values are zero).

2) Add equal height, equal width to Main view (i.e. which contains scrollview). For equal height set priority to low. (This is the important step for setting content size).

3) Height of this content view will be according to the number of views added to the view. let say if you added last view is one label and his Y position is 420 and height is 20 then your content view will be 440.

Step 3 : Add constraints to all of views which you added within content view as per your requirement.

For reference :

enter image description here

enter image description here

I hope this will definitely help you.

like image 69
Shrikant K Avatar answered Oct 13 '22 23:10

Shrikant K