12

iOS documention says, that the UIWebView class conforms to UIScrollViewDelegate. But an UIWebView instance does not call the scrollViewDidScroll method of its controller. The delegate is set just right by

[webView setDelegate:self];

and webViewDidFinishLoad is called successfully. The controller implements both delegates, UIWebViewDelegate and UIScrollViewDelegate, like this:

@interface WebviewController : UIViewController<UIWebViewDelegate, UIScrollViewDelegate>{
    UIWebView *webView;
}

Browsing SO leads to that category solution:

@implementation UIWebView(CustomScroll)
- (void) scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.delegate scrollViewDidScroll: scrollView];
}
@end

That category approach does basically the same: Calling the delegate's scrollViewDidScroll method. So why does the the first approach not work?

Community
  • 1
  • 1
alex
  • 2,464
  • 23
  • 32
  • 2
    did you set delegate for scrollView? `webView.scrollView.delegate = self` ? – pawelropa Aug 23 '12 at 14:28
  • No, I didn't. And yes, that works! – alex Aug 23 '12 at 14:37
  • So, a `UIWebView` instance sets its `scrollViews`'s delegate to that instance by default? Looks like... Otherwise the category approach would not work. – alex Aug 23 '12 at 14:48
  • To work this code have to set inside category scrolView delegate to webview and then inside UIWebView(CustomScroll) scrollViewDidScroll this message is send to through self.delegate (which is the delegate of UIWebView) to object which responds to webView delegate. So yes this code can work. – pawelropa Aug 23 '12 at 15:35

2 Answers2

29

My guess is you set up delegate only for UIWebView. Try setting delegate of scrollView.

webView.scrollView.delegate = self

it should be ok.

pawelropa
  • 1,409
  • 1
  • 14
  • 20
  • 1
    Consider using KVO on the `contentOffset` property of the child `scrollView` instead. It doesn't have to be safe to modify the delegate property of the `UIScrollView` since `UIWebView` can be using it internally. – lipka Jul 27 '15 at 16:50
0

This is not correct. If you will use:

@implementation UIWebView(CustomScroll)
- (void) scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.delegate scrollViewDidScroll: scrollView];
}
@end

You will lose focus when try to enter data on page on iOS7 and more

You need to implement custom class for UIWevView and overwrite scrollViewDidScroll:

- (void) scrollViewDidScroll:(UIScrollView *)scrollView{
[super scrollViewDidScroll:scrollView];
[((id<UIScrollViewDelegate>)self.delegate) scrollViewDidScroll:scrollView];}