Michal
Michal

Reputation: 15669

Listener for "Going back" in Navigation Controller

I found many old answers for this questions, but they all are 2+ years old.

I would like to add listener for the left button - the "back" one. I would like to show UIAlertView and then wait for response - YES/NO.

Is it possible in newer SDK?

Upvotes: 2

Views: 2571

Answers (4)

Son Nguyen
Son Nguyen

Reputation: 3481

Yes, you can do this by catching and handling event of back button yourself by:

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonPressed:)];

You can display an alert in the method:

- (void)backButtonPressed:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notice" message:@"Going back?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok"];
[alert show];
}

Then in the UIAlertDelegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) { // Button index: Cancel = 0; Ok = 1; 
        [self.navigationController popViewControllerAnimated:YES];
    }
}

Upvotes: 3

GnarlyDog
GnarlyDog

Reputation: 1247

It's not very clear what it is your trying to do. What object is doing the listening? The one on screen or one in the navigation stack but offscreen? What is the purpose of the UIAlertView? Do you require a response from the user? What should happen after the response?

There may be a way to add a KVO to a navigation bar property, but I'd think a better way (if you're targeting 5.0 and newer) would be to use a Custom Segue class. Using Custom Segues you can completely customize the entire transition process. If you wanted to see something in action, comment here with specifics of the behavior that you are looking for and I'll respond with an example.

Another option may be to subclass a UINavigationController which is also possible with 5.0 and newer, but I haven't tried this yet as I think it could potentially be opening a can of worms.

If you are targeting pre 5.0, I'd think the best way would be to use your own back button with the customized behavior.

Upvotes: 0

Stavash
Stavash

Reputation: 14304

You could "cheat" the system to show a custom UINavigationBar with your own arrow-shaped "Back" button - this way you could fully manipulate the behaviour and not be confined to the default behavior.

Upvotes: 2

melsam
melsam

Reputation: 4977

Here's one way to do it. I'm not sure if this is the only way, but this works for me:

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if (animated) {
        NSLog(@"User pressed Back button");

    }
}

Upvotes: 1

Related Questions