使用自定义视图设置右侧栏导航按钮后,按下按钮时永远不会调用选择器。这是我的代码:
UIImageView *navView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notification_alert.png"]];
navView.frame = CGRectMake(0, 0, 40, 40);
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navView];
[self.navigationItem.rightBarButtonItem setTarget:self];
[self.navigationItem.rightBarButtonItem setAction:@selector(BtnClick:)];
按钮显示正确但从不调用选择器。任何帮助将不胜感激!
-(IBAction)BtnClick:(id)sender
{
NSLog(@"nav button clicked");
}
答案 0 :(得分:1)
如 ndmeiri 所述
bar按钮项期望指定的自定义视图处理任何 用户互动
这就是你如何做到的:
UIImageView *navView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notification_alert.png"]];
navView.userInteractionEnabled = YES;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navView];
UITapGestureRecognizer *navViewTapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnClick:)];
[navViewTapRecognizer setNumberOfTouchesRequired:1];
[navView addGestureRecognizer:navViewTapRecognizer];
navView.userInteractionEnabled = YES;
行动:
-(void)btnClick:(id)sender
{
NSLog(@"nav button clicked");
}
但是,将自定义UIButton
设置为UIBarButtonItem
这就是你如何做到的:
UIButton *myButton = [[UIButton alloc] init];
myButton.frame=CGRectMake(0,0,40,40);
[myButton setBackgroundImage:[UIImage imageNamed: @"notification_alert.png"] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:myButton];
您还可以设置如下图像:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification_alert.png"]
style:UIBarButtonItemStylePlain
target:self
action:@selector(btnClick:)];
答案 1 :(得分:0)
来自init(customView:)
的文档:
此方法创建的条形按钮项不会调用其目标的操作方法以响应用户交互。相反,bar按钮项期望指定的自定义视图处理任何用户交互并提供适当的响应。
有关详细信息,请参阅UIBarButtonItem Class Reference。
解决方法是使用带有自定义背景图片的UIButton
作为自定义视图,而不是UIImageView
。然后,向按钮添加目标和操作。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 40, 40);
[button setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButtontem = [[UIBarButtonItem alloc] initWithCustomView:button];