所以,我想通了。
首先我设置了 webview 的委托,这样我就可以得到滚动事件并且可以检查 webview 是滚动到顶部还是底部:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if([scrollView isEqual:webView.scrollView]) {
float contentHeight = scrollView.contentSize.height;
float height = scrollView.frame.size.height;
float offset = scrollView.contentOffset.y;
if(offset == 0) {
webViewScrolledToTop = true;
webViewScrolledToBottom = false;
} else if(height + offset == contentHeight) {
webViewScrolledToTop = false;
webViewScrolledToBottom = true;
} else {
webViewScrolledToTop = false;
webViewScrolledToBottom = false;
}
//NSLog(@"Webview is at top: %i or at bottom: %i", webViewScrolledToTop, webViewScrolledToBottom);
}
}
然后我在 webview 的滚动视图中注册了额外的滑动手势识别器:
swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeUp)];
swipeUp.direction = UISwipeGestureRecognizerDirectionUp;
swipeUp.delegate = self;
[self.webView.scrollView addGestureRecognizer:swipeUp];
[self.webView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipeUp];
swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDown)];
swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
swipeDown.delegate = self;
[self.webView.scrollView addGestureRecognizer:swipeDown];
[self.webView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipeDown];
注意对[self.webView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipeUp]; 的调用。这些是绝对必要的,因为没有它们,webview 的平移手势识别器将始终在事件到达滑动手势识别器之前消耗事件。这些调用改变了优先级。
在 swipeUp 和 swipeDown 方法中,我计算下一个“页面”的位置并将父滚动视图滚动到该位置,如果确实有下一页。
最后一件事是,检查 webview 是滚动到顶部还是底部,并且只接受这种情况下的手势。因此,您必须实现手势识别器的委托:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if(gestureRecognizer == swipeUp) {
return webViewScrolledToBottom;
} else if(gestureRecognizer == swipeDown) {
return webViewScrolledToTop;
}
return false;
}
您可能还必须禁用滚动弹跳才能使此功能适用于网页太小以至于根本无法滚动:webView.scrollView.bounces = false;