gpt4 book ai didi

ios - 如何转发委托(delegate)的所有方法?

转载 作者:行者123 更新时间:2023-11-28 22:06:56 26 4
gpt4 key购买 nike

我正在子类化 UITableView 及其协议(protocol) UITableViewDelegate 及其“数据源”UITableDataSource,一切正常,但我还没有找到从 UITableView 转发来自“委托(delegate)”和“数据源”的方法的简洁方法。

我尝试“玩”respondsToSelector:forwardingTargetForSelector:forwardInvocation: NSObject 方法但我什么也没得到。

我将向您展示一些我正在尝试的代码:

我的CustomTableView.h:

@protocol TableViewCustomDelegate <UITableViewDelegate>

- (void) anyCustomMethodDelegate;

@end

@protocol TableViewCustomDataSource <UITableViewDataSource>

- (NSInteger) anyCustomMethod;

@end


@interface TableViewCustom : UITableView <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) id<TableViewCustomDelegate> myDelegate;
@property (nonatomic, weak) id<TableViewCustomDataSource> myDataSource;

@end

这是我的TableViewCustom.m:

@implementation TableViewCustom


-(BOOL)respondsToSelector:(SEL)aSelector {
if ([self.myDelegate respondsToSelector:aSelector]) {
return YES;
}
return [super respondsToSelector:aSelector];
}


-(id)forwardingTargetForSelector:(SEL)aSelector {
if ([self.myDelegate respondsToSelector:aSelector]) {
return self.myDelegate;
}
return [super forwardingTargetForSelector:aSelector];
}

...
...

- (void) setMyDelegate:(id<TableViewCustomDelegate>)delegate
{
[super setDelegate:self];
_myDelegate = delegate;
}

- (void) setMyDataSource:(id<TableViewCustomDataSource>)dataSource
{
[super setDataSource:self];
_myDataSource = dataSource;
}

..
..

// A method from UITableViewDelegate that I would like to avoid
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if ([self.delegateDelegate
respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
return [self.myDelegate tableView:tableView
viewForHeaderInSection:section];
}

return nil;
}

..
..

@end

我想避免仅将其转发给“myDelegate”的符合方法。

我认为它应该与 responsToSelector:forwardingTargetForSelector: 一起工作,就像我在我的代码中所做的那样,但它不起作用。我不知道是我做错了什么还是不可能。

提前致谢。

问候。

最佳答案

我可能误解了您的意图,但如果您只想让您的子类使用标准委托(delegate)和数据源,只需保留这些方法并将您想要的任何委托(delegate)/数据源交给子类即可。例如

MyTableViewSubclass *tableView = [[MyTableViewSubclass alloc] initWithFrame:....];
tableView.datasource = // anything that implements UITableViewDatasource
tableView.delegate = // anything that implements UITableViewDelegate

然后不要对子类中的这些属性或协议(protocol)做任何特殊的事情。

关于ios - 如何转发委托(delegate)的所有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23745674/

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