简体   繁体   中英

How to Programmatically Scroll iOS WKWebView, swift 4

So my question is: After a website(any websites on the www) has been loaded up in my iOS webview app how to make the app Programmatically Scroll vertically to any of the contents thats out of view?

//  ViewController.swift
//  myWebView

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

  @IBOutlet weak var myWebView: WKWebView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
  }

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear( animated )

    let urlString:String = "https://www.apple.com"
    let url:URL = URL(string: urlString)!
    let urlRequest:URLRequest = URLRequest(url: url)

    myWebView.load(urlRequest)
  }


  func webViewDidFinishLoad(_ webView: WKWebView) {

    let scrollPoint = CGPoint(x: 0, y: webView.scrollView.contentSize.height - webView.frame.size.height)
    webView.scrollView.setContentOffset(scrollPoint, animated: true )

  }
}

You can manipulate the Scroll View of the webview . Below there's an example to scroll to the bottom of the view:

let scrollPoint = CGPoint(x: 0, y: yourWebView.scrollView.contentSize.height - webView.frame.size.height)
webView.scrollView.setContentOffset(scrollPoint, animated: true)

This will also account for the possible horizontal offset of the origin of the scrollView:

var scrollPoint = self.view.convert(CGPoint(x: 0, y: 0), to: webView.scrollView)
scrollPoint = CGPoint(x: scrollPoint.x, y: webView.scrollView.contentSize.height - webView.frame.size.height)
webView.scrollView.setContentOffset(scrollPoint, animated: true)

If you want to get notify your wbeview reach to top or bottom use this extension, I made it long time ago for wkwebview. webview reach top or bottom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM