Search code examples
swiftactionbackbarbuttonitem

set navigation backBarButtonItem to go to specific UIViewController in Swift


I need the navigation's back button always pops a specific UIViewController.

override func viewDidLoad() {
    super.viewDidLoad()

    //set title image
    var logoImage:UIImage = UIImage(named: "barra")!
    var logoImageView : UIImageView = UIImageView(image: logoImage)
    logoImageView.frame = CGRectMake(0, 0, 320, 44)
    logoImageView.contentMode = .ScaleAspectFit
    logoImageView.contentMode = UIViewContentMode.Center
    logoImageView.clipsToBounds = true
    self.navigationItem.titleView = logoImageView

    //set back image
    var backImage:UIImage = UIImage(named: "freccia")!
    backImage = backImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .Plain,target: self, action: "goToServizi:")
    self.navigationController!.navigationBar.backIndicatorImage = backImage
    self.navigationController!.navigationBar.backIndicatorTransitionMaskImage = backImage

    //set menu image
    var menuImage:UIImage = UIImage(named: "menu")!
    menuImage = menuImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    self.navigationItem.rightBarButtonItem?.image = menuImage

}

func goToServizi(sender: UIBarButtonItem)
{
    self.navigationController?.popToViewController(ServiziVC(), animated: true)// here I add a breakpoint, but it is never executed.
}

ServiziVC is the UIViewController that I need to show every time I click on the Back button.

I can't understand why goToServizi func is not called. Please help.

Thank you.


Solution

  • Here is the example for you.

    import UIKit
    
    class SecondViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        //Customise your barButton Like this
        var backImage:UIImage = UIImage(named: "freccia")!
        backImage = backImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        var backButton = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.Bordered, target: self, action: "goToThird")
        self.navigationItem.leftBarButtonItem = backButton
    }
    
    func goToThird(){
    
        //Initiate newViewController this way
        let ThirdView = self.storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as ThirdViewController
    
        self.navigationController?.pushViewController(ThirdView, animated: true)
        }
    }
    

    EDIT

    Click on the ViewController which you want to initiate with identifier and you can find StoryBoard ID in Identity Inspector like shown in below Image.

    enter image description here

    HERE is the example for you for more reference.

    Modify code as per your need.may be this will help you.