How can I scroll programmatically to the bottom in a UIWebView?

后端 未结 4 1608
感情败类
感情败类 2020-12-28 22:14

I know a similar question has been asked before but it seemed never been answered. I have a UIWebView and add some content by string. I use UIWebView because I add some imag

相关标签:
4条回答
  • 2020-12-28 22:24

    This is how you can scroll down Animated:

    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
            CGPoint bottomOffset = CGPointMake(0, self.myWebView.scrollView.contentSize.height - self.myWebView.scrollView.bounds.size.height);
            [self.myWebView.scrollView setContentOffset:bottomOffset animated:YES];
    }
    
    0 讨论(0)
  • 2020-12-28 22:29

    SWIFT 4.x

    This is how you can scroll down Animated:

    func webViewDidFinishLoad(_ webView: UIWebView) {
        var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
        if (0.0 > scrollHeight) {
            scrollHeight = 0.0
        }
        webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
    }
    
    0 讨论(0)
  • 2020-12-28 22:30

    in iOS 5+ you could call the following method from your -(void)webViewDidFinishLoad:(UIWebView *)webView

    - (void)webViewScrollToBottom:(UIWebView *)webView
    {
        CGFloat scrollHeight = webView.scrollView.contentSize.height - webView.bounds.size.height;
        if (0.0f > scrollHeight)
            scrollHeight = 0.0f;
        webView.scrollView.contentOffset = CGPointMake(0.0f, scrollHeight);
    }
    
    0 讨论(0)
  • 2020-12-28 22:35

    This is fairly simple. First, you'll need to obtain height of the webpage:

    NSInteger height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue];
    

    Now you have the height of the document stored in the height variable. To scroll to bottom you have to use javascript again:

    NSString* javascript = [NSString stringWithFormat:@"window.scrollBy(0, %d);", height];   
    [webView stringByEvaluatingJavaScriptFromString:javascript];
    

    Of course you need to call them in proper moment. That is

    – webViewDidFinishLoad:(UIWebView *)webView
    

    method of your webview delegate.

    Hope this was helpful, Pawel

    0 讨论(0)
提交回复
热议问题