Detect a UIScrollView's height dynamically

2019-07-14 09:57发布

问题:

I have a real problem with detecting UIScrollView height. I searched a lot and found this solution:

So I dragged from Content View to View and made Equal Height. But I does not work for me.

I also tried to calculate scrollView height according to elements height in it, but I do not think that it's a right way.

How can I set UIScrollView height dynamically? What is the correct way for doing it?

回答1:

Your ScrollView should add a ContentView like this:

select your scrollView and in size Inspector bottom, set the width like this:

for more details on how to handle scrollView in Interface Builder your can check out this AppleDoc Working with Scroll Views

Hope this help you!



回答2:

You only way to set height of your scrollView is by calculating the height of individual objects added to scrollview.

Programatically, calculate the height of each UI object and at the end set content height to scrollview.

[scView setContentSize:CGSizeMake(300, height)];

In above line, 'height' is nothing but a sum of all heights of all UI objects calculated.



回答3:

By doing the below stuff's, I was able to implement UIScrollView with Automatic height based on the contents inside.

  1. Add scrollview to the main view.
  2. Add one ContentView inside this container scroll view.
  3. Give proper constraints inside this content view to the container scroll view as well as to its internal UI Components. Please note that you should not give fixed height to the content View. The constraints of the content view should grow according to the UI Components inside
  4. This might give you a layout warning as 'Unambigous.... '. To fix this, give 'Equal Heights' constraint relation between content view and scroll view

Try the above steps, and this will solve your issue :)



回答4:

Do you want to add item (UIView, UILabel...) in your UIScrollView by auto layout? If so, just put these in it and create correct constraints for them.

The key point is each item which in UIScrollView have top, leading, bottom and trailing side constraints to their superview. Most important is Make Sure that your UIScrollView has top, leading, bottom and trailing Descendant Constraints to its sub-items. It will calculate correct content height of scroll view for you.

In your solution, if your contentView has zero frame, it will not give you any height for scroll view.