UIScrollView with pagination + showing part of the

2019-03-07 23:36发布

问题:

I'm trying to create a kind of a "game mode" menu similar to the one used by the "Cut the Rope" game to select the level pack:

What I want in particular is to achieve the same effect of showing the "current item" (in this case, the "2. Fabric Box" item) plus a bit of the previous and following items (to make sure the user is aware that there are more modes available by scrolling), with pagination enabled (to make the scroll view automatically "center" on these items).

This seems like a natural job for a UIScrollView with pagination enabled, however from the documentation it seems the pagination occurs on multiples of the view bounds.

So: if pagination occurs on multiples of the view bounds, is there any way to achieve this effect with a UIScrollView?

The fact that we see the full width of the screen would suggest that the UIScrollView frame's width would be 320px in this case, but each individual item would need to be smaller than that in order to show that little bit of the previous and next items, thus messing up the pagination...

回答1:

For your reference, you can see a sample implementation of a page control from here. https://developer.apple.com/library/content/samplecode/PageControl/Introduction/Intro.html

For the implementation you want, to your surprise, the scrollview's width is actually smaller than 320 (or 480). The magic property to set is:

scrollView.clipsToBounds = NO

The only problem with this implementation is that the scrollview get no touch events if the touch is outside the bounds of the scrollView. This can be fix by passing its parent hitTest event to scrollView.

Just to link to to a better explanation: UIScrollView horizontal paging like Mobile Safari tabs

Slightly different from what I recommend but does the same thing.

Edit:

I have a small project called LXPagingViews that does the above, hopefully in an out of the box manner (Do drop me a pull request or feedback in issue): https://github.com/lxcid/LXPagingViews