Ricardo
Ricardo

Reputation: 8291

UIBarButtonItem event handling not working

I'm try to catch the event of back button and trigger the didClickBarButtonnLeft: method.

The following code does not work:

[self.navigationItem.leftBarButtonItem setTarget:self];
[self.navigationItem.leftBarButtonItem setAction:@selector(didClickBarButtonnLeft:)];

But this it does:

UIBarButtonItem* barButtonLeft;
 barButtonLeft = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:SIDE_VIEW_BAR_BUTTON]
                                                     style:UIBarButtonItemStylePlain
                                                    target:self
                                                    action:@selector(didClickBarButtonnLeft:)];

    self.navigationItem.leftBarButtonItem = barButtonLeft;

    [self.view setUserInteractionEnabled:YES];

The point is I don't want to replace the default back button icon. Both scripts are inside of -(void)viewDidAppear:(BOOL)animated method.

Upvotes: 1

Views: 115

Answers (1)

Brian Sachetta
Brian Sachetta

Reputation: 3463

I've got a couple things that could help. First, the best way to access the back button on the navigationItem is to say:

self.navigationItem.backBarButtonItem

Try using that instead of self.navigationItem.leftBarButtonItem and see if anything changes.

Secondly, if all you want to do is detect when the view controller is being removed from the navigation stack, you can override viewWillDisappear: and implement it like the following:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.isMovingFromParentViewController)
    {
        // call your back button pressed method
    }
}

Upvotes: 1

Related Questions