UIScrollView - setting proper contentOffset for ne

2019-07-20 08:18发布

问题:

I have been juggling for a while with UIScrollView now. What I am trying is to insert subviews into the scrollView based on various factors. Since I have scrollview to scroll only in vertical direction, I would insert the subview before or after the current visible view.

So, lets say my current visible view's frames are (0,0,320,480), the contentSize of scrollView is (320,480) and current contentOffset is (0,0)

When I want to insert subview above the currentView and yet keep the currentView in focus, I insert the new subview at the position (0,-480,320,480) and change the contentSize of scrollView to (320, 960) while keeping the contentOffset same as (0,0).

The surprising thing which happens is, UIScrollView adds "extra" space after the currentView instead of inserting it above the currentView. While the newly inserted view above can never be brought into focus coz UIScrollView is assuming the contentSize from a wrong contentOffset perhaps!

I googled and found that there are some others facing similar problems, but did not yield results yet: Set starting point of content size for UIScrollView

Please let me know if I am doing anything wrong? Or is this some kind of limitation etc?

Thanks!

Edit: Some threads suggests that changing the contentSize will affect contentOffset property, so to make sure that this is not causing problem, I am updating the contentOffset property only after I change the contentSize. Even then I am facing same problems.

回答1:

The origin is always (0,0). If you want to insert something above the current offset you'll want to move the current views down by 480 points, add the new view at (0,0) and set the contentOffset to (0,480) (and the contentSize to (320,960).



回答2:

You could solve this by :

  • adding your new subview with frame (0,0,320,480)
  • setting the frame of your existing subview to (0,480,320,480)
  • setting the contentSize to (320,960)
  • setting the content offset to (0,480) - not animated, of course.

So, in effect, moving everything down 480 points