webview监听contentOffset滚动事件

之前做了个页面是这样做的:

UIWebView 嵌入在 UIScrollerView上的,UIScrollerView是放在self.view上面的。
按这种UIWebView 嵌入在 UIScrollerView上的,然后执行代理方法,发现UIScrollerView的代理方法没有执行。

后来发现UIWebView 是继承UIview的,但是遵守 代理
提供的API接口的时候发现,UIWebView 有一个UIScrollerView的属性。

然后自己就设置下

webView.scrollerView.delegate = self。// 这个很重要啊

也就是设置了UIWebView的滚动代理方法,然后再执行,代理方法走通了。

-(UIWebView *)showWebView
{
    if (!_showWebView) {
        _showWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _showWebView.delegate = self;
        _showWebView.scrollView.delegate = self; 
    }
    return _showWebView;
}

#pragma mark - UIScrollViewDelegate 代理方法
  • (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {

    CGPoint translation = scrollView.contentOffset;
    if (translation.y < 0) {
    [UIView animateWithDuration:1.0 animations:^{
    [self atOnceTopAction];
    }];
    }else if(translation.y > 200){
    [UIView animateWithDuration:0.3 animations:^{
    }];
    }
    NSLog(@"%f",self.webViewLeft.scrollView.contentOffset.y);
    }

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{    
    NSLog(@"%f",scrollView.contentOffset.y);
//scrollView.contentOffset 会告诉你offset
        
}
下面这行代码是获取web view的实际高度

NSInteger htmlheight = [[self.showWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] integerValue];

亲测有用

你可能感兴趣的:(webview监听contentOffset滚动事件)