iosxcodeswiftuinavigationcontroller

Execute action when back bar button of UINavigationController is pressed


I need to execute an action (emptying an array), when the back button of a UINavigationController is pressed, while the button still causes the previous ViewController on the stack to appear. How could I accomplish this using swift? enter image description here


Solution

  • One option would be implementing your own custom back button. You would need to add the following code to your viewDidLoad method:

        - (void) viewDidLoad {
            [super viewDidLoad];
            self.navigationItem.hidesBackButton = YES;
            UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(back:)];
            self.navigationItem.leftBarButtonItem = newBackButton;
        }
    
        - (void) back:(UIBarButtonItem *)sender {
            // Perform your custom actions
            // ...
            // Go back to the previous ViewController
            [self.navigationController popViewControllerAnimated:YES];
        }
    

    UPDATE:

    Here is the version for Swift:

            override func viewDidLoad {
                super.viewDidLoad()
                self.navigationItem.hidesBackButton = true
                let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
                self.navigationItem.leftBarButtonItem = newBackButton
            }
    
           @objc func back(sender: UIBarButtonItem) {
                // Perform your custom actions
                // ...
                // Go back to the previous ViewController
                self.navigationController?.popViewControllerAnimated(true)
            }
    

    UPDATE 2:

    Here is the version for Swift 3:

            override func viewDidLoad {
                super.viewDidLoad()
                self.navigationItem.hidesBackButton = true
                let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
                self.navigationItem.leftBarButtonItem = newBackButton
            }
    
           @objc func back(sender: UIBarButtonItem) {
                // Perform your custom actions
                // ...
                // Go back to the previous ViewController
                _ = navigationController?.popViewController(animated: true)
            }