UIBarButtonItem不触发其动作方法

时间:2013-04-27 18:32:08

标签: ios objective-c uibarbuttonitem uitoolbar

在viewDidLoad中: - (void)viewDidLoad {     [super viewDidLoad];

[self.navigationController setNavigationBarHidden:YES animated:NO];

UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
NSMutableArray *toolBarItems = [[NSMutableArray alloc] init];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithTitle:@"Articles" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonTapped)]];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithTitle:@"Source" style:UIBarButtonItemStyleBordered target:self action:nil]];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithTitle:@"Aa" style:UIBarButtonItemStyleBordered target:self action:nil]];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithTitle:@"Rabbit" style:UIBarButtonItemStyleBordered target:self action:nil]];
[toolBar setBackgroundImage:[[UIImage alloc] init] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
toolBar.items = toolBarItems;
[self.view addSubview:toolBar];

方法:

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

我在方法内部有一个断点但它永远不会被调用。为什么这个方法永远不会被调用?

3 个答案:

答案 0 :(得分:5)

我在整个视图上有一个UITapGestureRecognizer拦截了UIBarButton上的点击。我解决了它,感谢this answer,它基本上停止了UITapGestureRecognizer的开始,除非它在UIToolBar之外。

答案 1 :(得分:1)

您的代码不完整,我不知道您是否没有实现它,或者只是没有在此处编写它,所以只是为了确保,这应该有效:

UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
NSMutableArray *toolBarItems = [[NSMutableArray alloc] init];
[toolBarItems addObject:[[UIBarButtonItem alloc] initWithTitle:@"Articles" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonTapped)]];
toolBar.items = toolBarItems;
[self.view addSubview:toolBar];

答案 2 :(得分:0)

试试这样。工作正常。

 UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    UIBarButtonItem *infoButton = [[UIBarButtonItem alloc]initWithTitle:@"back"style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonTapped)];
    [toolbar setItems:[NSArray arrayWithObjects:infoButton,nil]];
    [self.view addSubview:toolbar];