webview监听contentOffset滚动事件

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

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

后来发现UIWebView 是继承UIview的,但是遵守<NSCoding, UIScrollViewDelegate> 代理
提供的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];

亲测有用
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容