[英]Scroll to anchor in webView
We would like to open a WebView with a specific location opened in the view. 我们想打开一个在视图中打开了特定位置的WebView。 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. 我们试图在viewWillAppear
内部执行一个javascript,但是它不起作用。 If we execute it in the viewDidAppear
we have a jump to the anchor which is not a valid solution. 如果我们在viewDidAppear
执行它,我们将跳转到锚点,这不是有效的解决方案。
WebContentView (Simple Storyboard with a UIView
containing a single WebView): WebContentView(具有包含单个WebView的UIView
简单Storyboard):
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");
scrollTo(hash) {location.hash = "#" + hash;}; scrollTo("anchor");
How to scroll HTML page to given anchor using jQuery or Javascript? 如何使用jQuery或Javascript将HTML页面滚动到给定的锚点? 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. 如果您熟悉UIScrollView ,则应该知道可以使用setContentOffset方法。 By default, the UIWebView has a scrollView property: 默认情况下, UIWebView具有scrollView属性:
var scrollView: UIScrollView The scroll view associated with the web view. var scrollView:UIScrollView与Web视图关联的滚动视图。
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 : 另外 ,我认为您应该在webView完成加载后使用它,可以通过实现UIWebViewDelegate - webViewDidFinishLoad来实现:
func webViewDidFinishLoad(_ webView: UIWebView) {
webView.scrollView.setContentOffset(CGPoint(x: 0, y: 100), animated: true)
}
Hope this helped. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.