Jeff
Jeff

Reputation: 2699

UIWebView JavaScript troubles in iOS 5 (esp. window.pageYOffset and window.scrollTo)

This UIWebView code that worked fine under iOS 4 no longer works in iOS 5:

// webView is UIWebView loaded with a local PDF file
NString *s = [webView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"];

The contents of s is always "0" regardless of the actual position of the webView. and

// webPosition is the desired Y scroll position
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat: @"window.scrollTo(0, %d);", webPosition]];

Any ideas on a workaround to position the webView and read the position that works in iOS 5?

Upvotes: 1

Views: 1661

Answers (2)

Jeet
Jeet

Reputation: 363

You can use UIWebView's Scrollview for navigation as Javascript is no more supported in IOS5: Below code worked fine for me.

    [aWebView.scrollView setContentOffset:CGPointMake(x, y)];

The contentOffset accepts a CGPoint as argument. Here x and y are integer values representing the scrollPosition. If you want to get current x and y co-ordinates for webView, below is the code which you can use:

NSInteger x = aWebview.scrollView.contentOffSet.x;
NSInteger y = aWebview.scrollView.contentOffset.y;

Note: ScrollView is introduced in IOS 5 and will not work on earlier IOS versions. Javascript function are available for earlier versions. So you can check for device version and implement code accordingly.

Upvotes: 4

Jeff
Jeff

Reputation: 2699

Here's the answer, from MRL at Apple:

In iOS 5, we exposed the UIWebView's UIScrollView. You'd be better off just saving and restoring the contentOffset instead of trying to do this through javascript.

Upvotes: 0

Related Questions