如何以编程方式滚动 iOS WKWebView,swift 4

How to Programmatically Scroll iOS WKWebView, swift 4

所以我的问题是:在我的 iOS webview 应用程序中加载网站(www 上的任何网站)后,如何使应用程序以编程方式垂直滚动到视图之外的任何内容?

//  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 )

  }
}

您可以操纵 webviewScroll View。下面是一个滚动到视图底部的示例:

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

这也将考虑滚动视图原点的可能水平偏移:

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)

如果您想通知您的 wbeview 到达顶部或底部,请使用此扩展程序,我很久以前就为 wkwebview 制作了它。 webview reach top or bottom