views:

596

answers:

4

Hello,

I'm having a really hard time understanding delegates and object inheritance (if I may use this word) and I think I need a simple (or so I think) thing: catch scrollViewDidScroll event in UIWebView and get offset (basically, just to know if scroll is not on top/bottom, so I could hide navigation and tab bars).

Is there any way I could do it? I already using UIWebviewDelegate in my view controller to "shouldStartLoadWithRequest". Maybe I could some how use UIScrollViewDelegate too for scrollViewDidScroll? If yes, then how?

I really have trouble understanding delegates. I've red some articles, but still, in practice, I can't manage to use them.

Any help or info would be lovely.

Thank you in advance!

+1  A: 

It's a good question. UIWebView is not a subclass of UIScrollView, although I can see why one might think it is. That means using the UIScrollViewDelegate methods is not an option to do what you want, and the UIWebViewDelegate protocol does not respond to those scrolling event type of messages. I don't think there's an easy way to detect scrolling events in a web view.

No Surprises
+2  A: 

There is a scrolling view in the UIWebView, but it a) isn't a UIScrollView, and b) is something Apple considers a private implementation detail (and you should too). I only really have two suggestions:

  1. File a bug with Apple asking them to expose more of the infrastructure of the web view, or at least add some more delegate methods by which we can be notified of these sorts of events.
  2. Add some JavaScript code to your page that listens from scroll events, and notifies your app of them.

The basic foundation of #2 is to load a fake URL, and have your web view delegate process (and abort!) that load. (This question has come up a few times here on Stack Overflow.)

Sixten Otto
Thanks, for now I've ended up with different interface solutions for what I needed to do.So, there is no way one could access UIWebViews UIScroller and extract some offsets from it?
sniurkst
No documented/safe way, no. I'm sure that if you poke around in the UIWebView's view hierarchy with a debugger, you can probably come up with something, but it may break at any time. And Apple doesn't like undocumented APIs in the App Store. (OTOH, the JavaScript APIs inside the web view *are* well-documented and stable....)
Sixten Otto
+1  A: 

Hi ,

You can use the following methods to solve your problem.

For getting the pageOffset:

int pageYOffset = [[webViewObj stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];

For getting the total scroll height of a webpage:

int scrollHeight = [[webViewObj stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] intValue];

For scrolling the webpage to a particular offset:

[webViewObj stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollTop = %d",scrollHeight ]];

Biranchi