Search code examples
iosobjective-cobjective-c-runtime

Intercept Objective-C delegate messages within a subclass


I have a subclass of UIScrollView in which I need to internally respond to scrolling behaviour. However, the viewcontroller will still need to listen to scrolling delegate callbacks, so I can't outright steal the delegate within my component.

Is there a way to keep the property named "delegate" and just listen to messages sent along it, or else somehow internally hijack the delegate property and forward messages outward after running some code?


Solution

  • Yes, but you'll have to override every delegate method in the docs. Basically, make a second delegate property and implement the delegate protocol. When your delegate methods are called, take care of your business and then call the same method on your second delegate from the delegate method that was just run. E.g.

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        // Do stuff here
        if ([self.delegate2 respondsToSelector:@selector(scrollViewDidScroll:)]) {
            [self.delegate2 scrollViewDidScroll:scrollView];
        }
    }