是否可以从委托中调用原始委托?

Is it possible to call the original delegate from a delegate?

出于好奇,是否可以在自定义委托实现中调用原始委托方法实现。像 [super delegateMethod];或者这是不可能的。在某些情况下,如果满足某些条件,我会喜欢向行为添加自定义。提前致谢!

是的,这可以通过一个包装器对象来实现,该对象拦截消息并将它们转发给另一个委托对象。以下 class 拦截对 scrollViewDidScroll: 方法的调用,然后将其(以及任何其他委托方法调用)转发给另一个 UIScrollViewDelegate。

@import UIKit;

@interface ScrollHandler : NSObject <UIScrollViewDelegate>
- (instancetype)initWithScrollViewDelegate:(id<UIScrollViewDelegate>)delegate;
@end

@implementation ScrollHandler {
    id<UIScrollViewDelegate> _scrollViewDelegate;
}

- (instancetype)initWithScrollViewDelegate:(id<UIScrollViewDelegate>)delegate {
    self = [super init];
    if (self) {
        _scrollViewDelegate = delegate;
    }
    return self;
}

// Intercept specific method invocations:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // Implement custom behavior here before forwarding the invocation to _scrollViewDelegate
    [_scrollViewDelegate scrollViewDidScroll:scrollView];
}

// Forward unintercepted method invocations:

- (BOOL)respondsToSelector:(SEL)selector
{
    // Ask _scrollViewDelegate if it responds to the selector (and ourself as well)
    return [_scrollViewDelegate respondsToSelector:selector] || [super respondsToSelector:selector];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    // Forward the invocation to _scrollViewDelegate
    [invocation invokeWithTarget:_scrollViewDelegate];
}

@end

使用示例:

_scrollView = [[ScrollHandler alloc] init];
_scrollController = [[ScrollHandler alloc] initWithScrollViewDelegate:self];
_scrollView.delegate = _scrollController;