Emma
Emma

Reputation: 60

How to detect whether show (push) segue navigation controller is pressed?

I have two ViewControllers, first and second. They are connected with show (push) segue. I click button on firstViewController to go to secondViewController. Then using automatically added navigation controller <First , I go back to firstViewController. However, here I would like to get alert message when navigation controller to firstViewContoller is pressed. How do I do it?

Upvotes: 0

Views: 1594

Answers (2)

Hector Matos
Hector Matos

Reputation: 1056

What you are looking for is UINavigationControllerDelegate.

I believe the method that gives you the message you need is

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

And

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

In your CustomViewController, you are going to want to conform to the UINavigationControllerDelegate protocol like this:

@interface CustomViewController : UIViewController <UINavigationControllerDelegate>

And then override the delegate methods above to get the messages you are looking for.

Here is an complete implementation in Swift:

import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        println(viewController)
    }
}

class FirstViewController: ViewController {
}

class SecondViewController: ViewController {
}

Upvotes: 2

manecosta
manecosta

Reputation: 8772

You can work on the viewWillDisappear method on your second view controller like this:

- (void)viewWillDisappear:(BOOL)animated
{
    if(self.isMovingFromParentViewController){
        NSLog(@"Controller being popped");
    }
}

In this case, self.isMovingFromParentViewController will be true if the controller is being popped.

You can also check for self.isMovingToParentViewController on viewWillAppear for example, to check that the controller is being pushed.

Also self.isBeingDismissed and self.isBeingPresented are available and refer to when a controller is being presented/dismissed (modally).

Upvotes: 1

Related Questions