UIButton 作为 UIBarButttonItem 放置在导航栏上,点击时不会触发方法
UIButton placed as a UIBarButttonItem at the the Navigation bar won't trigger method when tapped
我创建了一个自定义 UIButton 并将其放在导航控制器的右侧。但是当我点击它时,它不会触发 buttonTapped 方法和打印输出 Testing 123,我做错了什么?
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIImage *btnImage = [[UIImage alloc] init];
BOOL unlike = NO;
if (unlike){
btnImage = [UIImage imageNamed:@"ic_favorite_border_48pt.png"];
}else{
btnImage = [UIImage imageNamed:@"ic_favorite_48pt.png"];
}
UIButton *heart = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect listButtonFrame = heart.frame;
listButtonFrame.size = btnImage.size;
heart.frame = listButtonFrame;
[heart setImage:btnImage forState:UIControlStateNormal];
[heart addTarget:self.navigationController.parentViewController
action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton = [[UIBarButtonItem alloc] initWithCustomView:heart];
self.navigationItem.rightBarButtonItem = jobsButton;
}
-(void)buttonTapped:(UIButton*)heart{
NSLog(@"Testing 123");
}
@end
[heart addTarget:self.navigationController.parentViewController
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
可能需要
[heart addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
我创建了一个自定义 UIButton 并将其放在导航控制器的右侧。但是当我点击它时,它不会触发 buttonTapped 方法和打印输出 Testing 123,我做错了什么?
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UIImage *btnImage = [[UIImage alloc] init];
BOOL unlike = NO;
if (unlike){
btnImage = [UIImage imageNamed:@"ic_favorite_border_48pt.png"];
}else{
btnImage = [UIImage imageNamed:@"ic_favorite_48pt.png"];
}
UIButton *heart = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect listButtonFrame = heart.frame;
listButtonFrame.size = btnImage.size;
heart.frame = listButtonFrame;
[heart setImage:btnImage forState:UIControlStateNormal];
[heart addTarget:self.navigationController.parentViewController
action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *jobsButton = [[UIBarButtonItem alloc] initWithCustomView:heart];
self.navigationItem.rightBarButtonItem = jobsButton;
}
-(void)buttonTapped:(UIButton*)heart{
NSLog(@"Testing 123");
}
@end
[heart addTarget:self.navigationController.parentViewController
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];
可能需要
[heart addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside];