I am trying to scroll to a particular page in a pdf document I have loaded in a UIWebView. I am able to do this without a problem in iOS 5 using:
pageHeight = webView.scrollView.contentSize.height / numberOfPages;
[[webView scrollView] setContentOffset:CGPointMake(0,pageNumber*pageHeight) animated:YES];
This only works however if the page has been loaded into the view already and the scroll to is triggered by a user action. For the case where I want to load a new pdf into the webview to a specific page, I am having trouble. I am requesting the load of the new pdf, and then doing something like the following when the page has completed loading:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
int contentHeight = myWebView.scrollView.contentSize.height;
int pageHeight = contentHeight / 5; // 5 total pages in example PDF
int scrollDelta = pageHeight*2; // Scroll forward 2 pages
[[myWebView scrollView] setContentOffset:CGPointMake(0,scrollDelta) animated:YES];
}
While myWebView.scrollView.contentSize.height is the full document height when I run similar code on a button click after the initial document loads, when I load a new document and webViewDidFinishLoad fires myWebView.scrollView.contentSize.height is equal to the height of the UIWebview, and not the content inside of it. This of course makes pageHeight much smaller than it needs to be and does not scroll to the correct position.
I've tried hacks like delaying the scroll code for a bit after webViewDidFinishLoad thinking maybe the page hasn't fully loaded even though I'm getting the callback, but in those cases contentSize.height is 0 for some reason.
Any ideas would be greatly appreciated.
Thanks!
to get the content size or the number of pages contained in the webview you may do the following:
float w = [[mywebview stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].scrollWidth;"] floatValue];
int pageCount = ceil(w/self.view.frame.size.width);
and to scroll to a certain position in your webview you may do the following:
[mywebview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(%d,0);",xPosition]];
You find it useful.
来源:https://stackoverflow.com/questions/9013754/uiwebview-content-height-not-accurate-in-scrollview-contentsize