gpt4 book ai didi

objective-c - 是否可以从委托(delegate)调用原始委托(delegate)?

转载 作者:行者123 更新时间:2023-12-03 17:50:42 25 4
gpt4 key购买 nike

出于好奇,是否可以在自定义委托(delegate)实现中调用原始委托(delegate)方法实现。像[ super 委托(delegate)方法];或者说这是不可能的。在某些情况下,如果满足某些条件,我希望添加自定义行为。预先感谢您!

最佳答案

是的,这可以通过包装器对象来实现,该包装器对象拦截消息并将它们转发到另一个委托(delegate)对象。以下类会拦截对scrollViewDidScroll: 方法的调用,然后将其(以及任何其他委托(delegate)方法调用)转发到另一个 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;

关于objective-c - 是否可以从委托(delegate)调用原始委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com