我将导航栏子类化,使标题视图可点击。单击时,它将呈现另一个视图控制器。我正在导航栏中创建一个协议,它将告诉导航控制器标题视图已被单击。这是我的导航栏的定义方式:
导航栏.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
文件如下:
导航栏.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];
}
这将创建一个带有徽标的导航栏,并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
?我需要在导航控制器中做些什么吗?我只是使用普通的 old UINavigationController
。我也需要子类化吗?如果是这样,为什么?
编辑:
po self.delegate
在线调用[self.delegate titleViewClicked:_titleClicked];
会NavigationBar.m
产生以下结果。委托是如何改变其类型的?我该如何解决?
(lldb) po self.delegate
(objc_object *) $1 = 0x07550170 <UINavigationController: 0x7550170>