Website Links

Friday 1 May 2015

Preventing Backwards Navigation from a Bar Button Item in Swift

Hello there, sometimes you wish to return to the root view controller when you click on a bar button item in the navigation bar of an app with a navigation controller. For example, you may save something that you don't want the user to be able to go back to. Fortunately, there is away to do this and it is by using a segue with an identifier.
  1. Create a segue from your Bar Button Item
  2. Click on your segue and give it an identifier
  3. Implement the following function in the view controller which has the bar button you added a segue for:

    override func shouldPerformSegueWithIdentifier(identifier: 
        String?, sender: AnyObject?) -> Bool {
        
        if (identifier == "save") {
            saveBoard()
        }
        
        self.navigationController?
            .popToRootViewControllerAnimated(true)
        
        return false
    }


The above handles 2 different segues in my project, one is cancel in which case I want to return to the root view controller without having the ability to go back to my board that I decided I no longer wanted to save. The other is save, when my saving segue is called I want to call my function which saves the board and then goes back to the root view controller. The boolean returned by the function specifies whether the segue was cancelled or not... I returned false as I wanted to handle the navigation back to the root view controller by myself in all cases. The function shouldPerformSegueWithIdentifier could also be useful to implement if you wanted to validate the data a user entered before navigation.

No comments:

Post a Comment