Hanz Cheah
Hanz Cheah

Reputation: 811

UIButton placed as a UIBarButttonItem at the the Navigation bar won't trigger method when tapped

I have created a custom UIButton and placed it at the right hand side of the navigation controller. But when I tapped on it, it doesn't trigger the buttonTapped method and printout Testing 123, what have I done wrong?

- (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

Upvotes: 2

Views: 60

Answers (1)

Todanley
Todanley

Reputation: 508

[heart addTarget:self.navigationController.parentViewController
           action:@selector(buttonTapped:)
 forControlEvents:UIControlEventTouchUpInside];

Probably needs to be

[heart addTarget:self
           action:@selector(buttonTapped:)
 forControlEvents:UIControlEventTouchUpInside];

Upvotes: 3

Related Questions