拦截子类中的Objective-C委托消息

拦截子类中的Objective-C委托消息

问题描述:

我有UIScrollView的子类,我需要在内部对滚动行为做出响应.但是,viewcontroller仍将需要侦听滚动的委托回调,因此我无法彻底窃取组件中的委托.

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.

是否有一种方法可以保留名为"delegate"的属性并仅侦听沿其发送的消息,或者以某种方式在内部内部劫持委托属性并在运行一些代码后向外转发消息?

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?

是的,但是您必须覆盖

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];
    }
}