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:
scrollTo(hash) {location.hash = "#" + hash;}; scrollTo("anchor");
scrollTo(hash) {location.hash = "#" + hash;}; scrollTo("anchor");
How to scroll HTML page to given anchor using jQuery or Javascript? How can we accomplish a "smooth" scroll to the anchor or a jump before it is visible?
If you are familiar with UIScrollView , you should know that you can use setContentOffset method. By default, the UIWebView has a scrollView property:
var scrollView: UIScrollView The scroll view associated with the web view.
So, what you can do -for example- is:
webView.scrollView.setContentOffset(CGPoint(x: 0, y: 100), animated: true)
Also , I think you should use it after the webView finished loading, you can achieve this by implementing UIWebViewDelegate - webViewDidFinishLoad :
func webViewDidFinishLoad(_ webView: UIWebView) {
webView.scrollView.setContentOffset(CGPoint(x: 0, y: 100), animated: true)
}
Hope this helped.
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.