Execute action when back bar button of UINavigationController is pressed
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
}
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
}
func back(sender: UIBarButtonItem) {
// Perform your custom actions
// ...
// Go back to the previous ViewController
_ = navigationController?.popViewController(animated: true)
}
Detect if default back button in navigation bar is pressed
In your viewWillDisappear method, add the isMovingFromParentViewController
property:
if self.isMovingFromParentViewController {
//do stuff, the back button was pressed
}
EDIT: As had pointed out, if you are merely dismissing the view controller when the save button is pressed, you need a Bool
value to check if the save button was pressed or the default back button.
At the top of your class, define a Boolean value:
var saveButtonPressed = false
I'm assuming that you have an @IBAction
method linked to your save button. If you don't, then I suggest you add that connection.
In that method, set saveButtonPressed
equal to true.
Then, in your viewWillDisappear method, add this to the if condition:
if (self.isMovingFromParentViewController && !saveButtonPressed) {
//do stuff, the back button was pressed
}
Trying to handle back navigation button action in iOS
Try this code using VIewWillDisappear
method to detect the press of The back button of NavigationItem:
-(void) viewWillDisappear:(BOOL)animated
{
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound)
{
// Navigation button was pressed. Do some stuff
[self.navigationController popViewControllerAnimated:NO];
}
[super viewWillDisappear:animated];
}
OR There is another way to get Action of the Navigation BAck button.
Create Custom button for UINavigationItem of back button .
For Ex:
In ViewDidLoad :
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
self.navigationItem.leftBarButtonItem=newBackButton;
}
-(void)home:(UIBarButtonItem *)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
Swift :
override func willMoveToParentViewController(parent: UIViewController?)
{
if parent == nil
{
// Back btn Event handler
}
}
Go back to root when nav back button is press
Personally I would not recommend what you are trying to achieve, but anyways here is a different solution without customizing the back button.
Steps to implement
- Create CustomNavigationController by subclassing
UINavigationController
- Override
popViewController(animated:)
- When
ViewController
conforms toNavigationable
andshouldCustomNavigationControllerPopToRoot()
returnstrue
, callsuper.popToRootViewController
- Otherwise proceed with normally popping the
ViewController
Source Code
Custom Navigation Controller
import UIKit
class CustomNavigationController: UINavigationController {
// MARK: - Initializers
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
initialSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
// MARK: - Setups
private func initialSetup() {
// DISCLAIMER: This code does not support `interactivePopGestureRecognizer`, therefore we disable it
interactivePopGestureRecognizer?.delegate = nil
}
// MARK: - Overrides
override func popViewController(animated: Bool) -> UIViewController? {
if shouldNavigationPopToRoot {
return super.popToRootViewController(animated: animated)?.last
}
return super.popViewController(animated: animated)
}
// MARK: - Helpers
private var shouldNavigationPopToRoot: Bool {
return (topViewController as? Navigationable)?.shouldCustomNavigationControllerPopToRoot() == true
}
}
View Controller conforming to Navigationable
import UIKit
protocol Navigationable: class {
func shouldCustomNavigationControllerPopToRoot() -> Bool
}
class ViewController: UIViewController, Navigationable {
// MARK: - Protocol Conformance
// MARK: Navigationable
func shouldCustomNavigationControllerPopToRoot() -> Bool {
return true
}
}
Output
UINavigationController and back button action
Or you can use the UINavigationController
's delegate methods. The method willShowViewController
is called when the back button of your VC is pressed.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
Related Topics
Outlets Cannot Be Connected to Repeating Content Ios
Swiftui App Life Cycle Ios14 Where to Put Appdelegate Code
How to Support Universal Links in iOS App and Setup Server For It
Navigation Bar With Uiimage For Title
How to Add Objects to a Uiscrollview That Extend Beyond Uiview from Storyboard
How to Make a Push Segue When a Uitableviewcell Is Selected
Changing Specific Text's Color Using Nsmutableattributedstring in Swift
Programmatically Open Maps App in iOS 6
How to Navigate from One View Controller to Another Using Swift
Ios: How to Share Text and Image on Social Networks
Swift Saving and Retrieving Custom Object from Userdefaults
Uibutton Action in Table View Cell
Asynchronous Downloading of Images For Uitableview With Gcd
Swift Native Functions to Have Numbers as Hex Strings
Add Image to Uialertaction in Uialertcontroller
How to Get the Color of a Pixel in a Uiimage With Swift
Disable Gesture to Pull Down Form/Page Sheet Modal Presentation