代表发送到错误的类

我subclassed我的导航栏,使标题视图可点击。 点击后,会显示另一个视图控制器。 我正在导航栏中创build一个协议,这将告诉导航控制器标题视图已被点击。 以下是我的导航栏的定义:

NavigationBar.h:

@protocol NavigationBarDelegate; @interface NavigationBar : UINavigationBar { id <NavigationBarDelegate> delegate; BOOL _titleClicked; } @property (nonatomic, assign) id <NavigationBarDelegate> delegate; @end @protocol NavigationBarDelegate @optional - (void)titleButtonClicked:(BOOL)titleClicked; @end 

委托实现一个可选的方法。 .m文件如下所示:

NavigationBar.m:

 @implementation NavigationBar - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _titleClicked = 0; } return self; } - (void)drawRect:(CGRect)rect { self.tintColor = [UIColor colorWithRed:(111/255.f) green:(158/255.f) blue:(54/255.f) alpha:(255/255.f)]; UIImage *image = [UIImage imageNamed:@"titlelogo.png"]; UIButton *titleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)]; titleButton.backgroundColor = [UIColor colorWithPatternImage:image]; [titleButton addTarget:self action:@selector(titleButton:) forControlEvents:UIControlEventTouchUpInside]; // self.navigationController.delegate = self; [self.topItem setTitleView:titleButton]; [super drawRect:rect]; } - (void)titleButton:(UIButton *)sender { _titleClicked = !_titleClicked; [self.delegate titleButtonClicked:_titleClicked]; } 

这将创build一个带有徽标的导航栏,并在标题button被点击时调用titleButton方法。 一切都很好,直到这里和导航栏很好地显示。

在我的RootViewController

 NavigationBar *navigationBar = [[NavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44.0f)]; navigationBar.delegate = self; [self.navigationController setValue:navigationBar forKey:@"navigationBar"]; 

titleButtonClicked的实现也在那里。 当我点击标题视图,但是我得到以下错误: -[UINavigationController titleButtonClicked:]: unrecognized selector sent to instance

为什么我得到titleButtonClicked发送到UINavigationController ? 我的导航控制器中有什么需要做的吗? 我只是使用普通的旧UINavigationController 。 我是否也需要子类? 如果是这样,为什么?

编辑:

在线上调用po self.delegate [self.delegate titleViewClicked:_titleClicked];NavigationBar.m产生下面的结果。 代表如何改变其types? 我该如何解决这个问题?

 (lldb) po self.delegate (objc_object *) $1 = 0x07550170 <UINavigationController: 0x7550170> 

您的delegateUINavigationBardelegate属性之间有冲突/不明确之处。 重命名您的委托以消除它们的歧义。

正如@idz所说,问题出在你的:

 @property (nonatomic, assign) delegete; 

难道你没有看到,你甚至没有一个奇怪的:

 @synthesize delegete; 

这是因为UINavigationBar已经定义了一个delegatevariables,就像idz所说的那样。

将您的声明更改为:

 // use unsafe_unretained in ARC, not assign @property (nonatomic, unsafe_unretained) myDelegete; 

而且当然

 @synthesize myDelegate;