How do I scroll a WebView of an HTML string to a specific anchor?
I'm wondering how to scroll programmatically to a given anchor in a WebView.
The content I am showing is rendered by
[[webView mainFrame] loadHTMLString:htmlString baseURL:someURL];
and thus I cannot simply navigate to #anchors by pointing them out in the URLs.
I'm looking for a method along the lines of
[[webView mainFrame] scrollToAnchor:@"anchor"]
but obviously it isn't there.
T开发者_JS百科IA
Using Javascript Bridge works, but you can also do the equivalent from Objective-C if you like:
DOMDocument *doc = [[webView mainFrame] DOMDocument];
DOMElement *element = [doc getElementById:@"anchor"];
[element scrollIntoView:YES];
- (void)viewDidLoad
{
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"YOUR_STRING_WITHOUT_ANCHOR"]]];
}
- (void)webViewDidStartLoad:(UIWebView *)_webView {
[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('YOUR_ANCHOR_HERE_WITHOUT_#').scrollIntoView(true);"];
}
Ok, found a workaround, but I don't know if this is the right way to do it. By getting the reference to the javascript context I can call javascript methods in the webFrame.
[[webView windowScriptObject] evaluateWebScript:@"document.getElementById('TheId').scrollIntoView(true);"];
精彩评论