Intercept Objective-C delegate messages within a subclass

前端 未结 4 729
渐次进展
渐次进展 2020-12-04 08:13

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 c

4条回答
  •  感情败类
    2020-12-04 08:43

    Actually, this worked for me:

    @implementation MySubclass {
        id _actualDelegate;
    }
    
    // There is no need to set the value of _actualDelegate in an init* method
    - (void)setDelegate:(id)newDelegate {
        [super setDelegate:nil];
        _actualDelegate = newDelegate;
        [super setDelegate:(id)self];
    }
    
    - (id)delegate {
        return self;
    }
    
    - (id)forwardingTargetForSelector:(SEL)aSelector {
        if ([_actualDelegate respondsToSelector:aSelector]) { return _actualDelegate; }
        return [super forwardingTargetForSelector:aSelector];
    }
    
    - (BOOL)respondsToSelector:(SEL)aSelector {
        return [super respondsToSelector:aSelector] || [_actualDelegate respondsToSelector:aSelector];
    }
    @end
    

    ...making the subclass to be the message interceptor in the awesome answer given by e.James.

提交回复
热议问题