选择器未被调用以处理导航栏按钮。

3

我使用自定义视图设置了正确的导航栏右侧按钮,但当按下该按钮时,选择器从未被调用。以下是我的代码:

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");
}

https://dev59.com/lHM_5IYBdhLWcg3wzmnL - DogCoffee
2个回答

2
< p > 正如 ndmeiri 提到的

< blockquote>

工具栏按钮项期望指定的自定义视图处理任何用户交互

以下是操作方法:

   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:)];

不确定为什么这被投票否决,因为它按预期工作...我尝试了定制方法,但图像太大,所以我需要在使用第一种方法之前调整大小。 - gumbynr
@gumbynr 可能是因为我发布了没有解释的代码,我本来想在粘贴代码后编辑答案。无论如何,我已经用更好的方法更新了代码。请检查第二个解决方案。如果它有效,您可以更正对此答案的投票。 - Alaeddine

0

init(customView:)的文档中:

通过此方法创建的工具栏按钮项不会在用户交互时调用其目标的操作方法。相反,工具栏按钮项期望指定的自定义视图处理任何用户交互并提供适当的响应。

有关更多信息,请参见UIBarButtonItem类参考

解决方法是使用带有自定义背景图像的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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接