user2328703
user2328703

Reputation: 225

BackButton title does change but action doesn't

I'm trying to change the action of a specific back button but for some reason it doesn't call the method i'm giving him. This is weird cause the title does change so i figured it should also work for the action. This is my code for the button:

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle: @"Back"
                                   style: UIBarButtonItemStyleBordered
                                   target:self action: @selector(goBackToChooseMovie)];

[self.navigationItem setBackBarButtonItem: backButton];

This is my method:

-(void)goBackToChooseMovie{

    ViewController *VC = (ViewController *)[self.navigationController.viewControllers objectAtIndex:0];
    VC.showingPhotoLibraryFromCamera = YES;

    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:NO];

}

Upvotes: 0

Views: 263

Answers (2)

Bhavin
Bhavin

Reputation: 27225

This is never going to work as you can't change the nature of Back button. Apple has pre-defined rules for the components provided by them. There are two options :

1) If you want to call your custom method only then you can create one custom button with some "back" image and then assign it to leftBarButtonItem.

UIImage* image = [UIImage imageNamed:@"backButton.png"];
CGRect frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIButton *back = [[UIButton alloc] initWithFrame:frame];
[back setBackgroundImage:image forState:UIControlStateNormal];
[back addTarget:self action:@selector(goBackToChooseMovie) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = leftBarButton;

2) You can use -viewWillDisappear :

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
       // back button was pressed. 
    }
    [super viewWillDisappear:animated];
}

Upvotes: 1

jamil
jamil

Reputation: 2437

You should change your code

[self.navigationItem setBackBarButtonItem: backButton];

to

self.navigationItem.leftBarButtonItem = backButton;

Hope it works for you.

Thanks

Upvotes: 0

Related Questions