How to Programmatically Scroll iOS WKWebView, swift 4

我怕爱的太早我们不能终老 提交于 2020-01-15 09:43:34

问题


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 )

  }
}

回答1:


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)



回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/51659208/how-to-programmatically-scroll-ios-wkwebview-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!