Make subview of a UIScrollView fixed while the oth

2020-06-04 04:08发布

问题:

I want to make a View with three subviews stacked on top of each other with the middle subview scrollable with the others fixed.

How can I achieve this programmatically? I have tried

  • to set the contentsize of the root view to the size of the scrollable view but that makes all the views scroll.

-set the contentsize of the middle subview without setting any property for the root view but that makes all the views unscrollable.

Please help. I am new to iOS.

Thanks in advance

回答1:

You can use the scrollViewDidScroll: delegate callback on the UIScrollView to adjust your view's position. In the callback, get the contentOffset of the scrollview and use that to set your fixed view's position.

For example, if you want your fixed view to always remain 100 px from the top of the scrollview, set its initial frame to (0, 100, width, height), and then in the callback set the frame to (0, contentOffset.y + 100, width, height).

The result is that the subview will appear fixed at a given height.



回答2:

If your UIScrollView has a superview (i.e. a container view), you can add your 'fixed' view as a subview of the superview instead of the UIScrollView. You'll only have to calculate your frame coordinates once.



回答3:

You can do it moving sub view from UIScrollView to super view of scrollview like:

Place/set your button over scroll view (not inside scroll view) as shown here in this snapshot. And also set button constraints (position) with respect to super view of your scrollview.

Here is ref. snapshot of hierarchy of position of each view over each-other.