How to Programmatically Scroll iOS WKWebView, swift 4
Asked Answered
G

3

5

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 )

  }
}
Gnotobiotics answered 2/8, 2018 at 17:27 Comment(2)
Do you have any relevant code you can show us? That usually helps generate answers.Decima
yes, the code has been postedGnotobiotics
A
4

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)
Andromada answered 29/11, 2018 at 15:21 Comment(0)
K
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)
Kilmarnock answered 2/8, 2018 at 17:42 Comment(1)
Thanks for helping João Fernandes, i edit my post with your answer to give some context as to what i need to do further to get your code to work. Any help would be greatly appreciated.Gnotobiotics
C
0

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

Clique answered 30/11, 2018 at 4:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.