We would like to open a WebView with a specific location opened in the view. Therefore we would like to scroll to an anchor OR jump to it before it is shown.
We tried to execute a javascript inside of the viewWillAppear
, but it does not work. If we execute it in the viewDidAppear
we have a jump to the anchor which is not a valid solution.
WebContentView (Simple Storyboard with a UIView
containing a single WebView):
class WebContentViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var fileName: String?
var screenName: String?
override func viewDidLoad() {
super.viewDidLoad()
webView.backgroundColor = UIColor.white
let url = URLRequest(url: Bundle.main.url(forResource: fileName, withExtension: "html")!)
webView.loadRequest(url);
webView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let screenName = screenName else {
return
}
webView.stringByEvaluatingJavaScript(from: "window.location.href = '#2-einsatz-von-google-analytics';")
}
override func viewDidAppear(_ animated: Bool) {
//webView.stringByEvaluatingJavaScript(from: "window.location.href = '#2-einsatz-von-google-analytics';") //creates a jump instead of a scrole
}
}
Tried solutions and known questions:
- Using
scrollTo(hash) {location.hash = "#" + hash;}; scrollTo("anchor");
How to scroll HTML page to given anchor using jQuery or Javascript? - Is it possible to send a hash tag to a file url in UIWebView?
How can we accomplish a "smooth" scroll to the anchor or a jump before it is visible?