Paging UIScrollView with peeking neighbor pages

2019-01-22 04:39发布

Look at the App Store app, on either the iPhone or the iPad, specifically the piece on the screen of app details that shows screenshots. The screenshot viewer shows you the screenshot you're looking at, and the edges of the next and previous one. I need to implement something much like that.

How I've done it is fair to poor: I built a UIScrollView and enabled paging and laid out my content. I made the frame be the same size as a page of content, but smaller than the screen. Then I disabled clipToBounds, so whatever's outside the frame of the ScrollView still gets drawn. Now I can SEE the edges of the adjacent pages, but they're outside the ScrollView and so can't receive scroll touches. The App Store app lets you touch the whole width of that thing, including the peeking edges of the neighboring pages.

So how'd they do that?

3条回答
贼婆χ
2楼-- · 2019-01-22 04:58

Don't forget to forward the touches to the scrollview subviews if you want your content to stay interactive outside the bounds.

The following example is true if you've put your scrollview content in an extra container. If this isn't the case, the loop over the subviews and return the one that gets hit by your touch.

- (UIView*)hitTest:(CGPoint)pt withEvent:(UIEvent*)event 
{
    UIView *contentView = [self.subviews count] ? [self.subviews objectAtIndex:0] : nil;
    return [contentView hitTest:pt withEvent:event];
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-22 05:09

I don't have a high enough ranking to comment on the answers above but you can find a tutorial and sample code on Ray Wenderlich's site: How To Use UIScrollView to Scroll and Zoom Content

This code does use the techniques listed above, specifically the hit test logic.

查看更多
贪生不怕死
4楼-- · 2019-01-22 05:13

You need to add a view 'behind' the scroll view which covers the entire area where your pages will be visible. This view should implement -hitTest:withEvent:. This method will get called by the OS to determine where to route a particular touch event. All you need to do is return your scroll view for any points within this backing view:

- (UIView *) hitTest: (CGPoint) pt withEvent: (UIEvent *) event {
    if (CGRectContainsPoint(self.bounds, pt)) return self.scrollView;
    return [super hitTest: pt withEvent: event];
}
查看更多
登录 后发表回答