Ios 未为navigationitem barbutton调用选择器
在我使用自定义视图设置了右栏导航按钮之后,当按下按钮时,永远不会调用选择器。这是我的密码:Ios 未为navigationitem barbutton调用选择器,ios,objective-c,Ios,Objective C,在我使用自定义视图设置了右栏导航按钮之后,当按下按钮时,永远不会调用选择器。这是我的密码: UIImageView *navView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notification_alert.png"]]; navView.frame = CGRectMake(0, 0, 40, 40); self.navigationItem.rightBarButtonItem = [[UIBarButton
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");
}
从
init(customView:)
的文档中:
此方法创建的条形按钮项不调用其目标的action方法来响应用户交互。相反,bar button项期望指定的自定义视图处理任何用户交互并提供适当的响应
有关更多信息,请参阅
解决方法是使用带有自定义背景图像的ui按钮
作为自定义视图,而不是ui图像视图
。然后,向按钮添加目标和操作
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];
正如恩德梅里所提到的
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:)];
不知道为什么这被否决了,因为它按计划工作。。。我尝试了自定义的方法,但是图像太大了,所以我需要在使用第一个方法之前调整大小method@gumbynr可能是因为我没有解释就发布了代码,所以我打算在粘贴代码后编辑答案。无论如何,我已经用更好的方法更新了代码。检查第二个解决方案。如果可行的话,你可以更正对这个答案的投票