Reputation: 85
I have a ViewController with a UIWebView, in a Objective-c project for iPad. When I add html (with loadHtmlString), I try to keep the scroll position it had before the loadHtml, but I cannot help and it returns to the top. Here are the lines I use:
scrollPosition = [[webView stringByEvaluatingJavaScriptFromString: @"scrollY"] intValue];
[webView loadHTMLString:html baseURL:nil];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0, %d);",scrollPosition]];
I tested the value 'scrollY' at different locations in my code and it stays at the value scrollPosition that I want, but when it ends up showing on the screen the WebView is always at the top (with the scrollY value then to 0). Is there someone who could help me figure out why this happens?
I checked for hours the answers online, also on StackOverflow. I tried different solutions (like adding in my webview the JavaScript "onclick="scroll(); return false;", but to no avail. I tried to self-delegate the webView and update the scrollTo in webViewDidFinishLoad, but it seems that webViewDidFinishLoad is not called (the breakpoint is not reached) although I did add in .h in the interface and in the .m in ViewDidLoad the line: webView.delegate=self;
Thank you in advance for any help.
Upvotes: 2
Views: 837
Reputation: 85
I realized that after recompiling, webViewDidFinishLoad was called after the html was updated, and that I could then scroll to the correct position. For the self delegation I used in viewDidLoad, it looks so:
webview.delegate = self;
Before updating the html in the webView I calculate the scrolling position with the code:
scrollPosition = [[wbView stringByEvaluatingJavaScriptFromString: @"scrollY"] intValue];
Then, for moving back to this position once the webView has an updated html, I then use:
-(void) webViewDidFinishLoad:(UIWebView *)wbView {
[wbView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0, %d);",scrollPosition]];
}
I found part of the solution through the post below, with the answer of Pawel: How can I scroll programmatically to the bottom in a uiwebview
Upvotes: 3