您引用的那个答案是我最喜欢的答案之一。它没有考虑您的第一个要求,但我认为只需添加一个轻击手势识别器,它就可以非常巧妙地处理它。
在您的“ClipView”上创建它:
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.myClipView addGestureRecognizer:tapGR];
// myClipView is the view that contains the paging scroll view
- (void)tap: (UITapGestureRecognizer *)gr {
// there are a few challenges here:
// 1) get the tap location in the correct coordinate system
// 2) convert that to which "page" was tapped
// 3) scroll to that page
}
挑战 1) 很容易感谢手势识别器,它回答locationInView:
CGPoint location = [gr locationInView:self.scrollView];
对于挑战 2),我们需要确定您的滚动视图中的哪个页面被点击了。给定页面宽度,这可以通过非常简单的算术来完成。
// assuming you have something like this
#define kPAGE_WIDTH // some float
// page is just how many page-width's are represented by location.y
NSInteger page = floor(location.y/kPAGE_WIDTH);
现在,挑战 3) 现在很容易,因为我们可以直接将页面更改为它的滚动位置......
CGFloat y = page * kPAGE_WIDTH;
[self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];
或者,全部在一块代码中......
- (void)tap: (UITapGestureRecognizer *)gr {
CGPoint location = [gr locationInView:self.scrollView];
NSInteger page = floor(location.y/kPAGE_WIDTH);
CGFloat y = page * kPAGE_WIDTH;
[self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];
}
编辑
您可能还想从手势识别器中排除“当前页面”区域。这只是通过在 tap 方法中限定测试来完成的。
唯一的技巧是在与滚动视图的框架相同的坐标系中获取点击位置,即剪辑视图......
CGPoint locationInClipper = [gr locationInView:gr.view];
SDK 提供了一个很好的测试方法......
BOOL inScrollView = [self.scrollView pointInside:locationInClipper withEvent:nil];
所以...
- (void)tap: (UITapGestureRecognizer *)gr {
CGPoint locationInClipper = [gr locationInView:gr.view];
BOOL inScrollView = [self.scrollView pointInside:locationInClipper withEvent:nil];
if (!inScrollView) {
CGPoint location = [gr locationInView:self.scrollView];
NSInteger page = floor(location.y/kPAGE_WIDTH);
CGFloat y = page * kPAGE_WIDTH;
[self.scrollView setContentOffset:CGPointMake(y, 0.0f) animated:YES];
}
}