How can I set the backBarButtonItem action to swift?

How can I set the backBarButtonItem action and still display the left arrow?

I used this code but the arrow was not displayed

var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:")
self.navigationItem.leftBarButtonItem = barBack

      

but when i used this code the action doesn't work

self.navigationController?.navigationBar.topItem?.backBarButtonItem = barBack

      

thank

+3


source to share


3 answers


As an alternative to customizing the action, you can save backBarButtonItem

and use isMovingFromParentViewController

instead to handle the logic to move back onto the navigation stack.



override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParentViewController() {
        .. do something here
    }
}

      

+2


source


try it

var barBack = UIBarButtonItem(title: "Reset", style: UIBarButtonItemStyle.Plain, target: self, action: "reset:")
self.navigationItem.leftBarButtonItem = barBack

      



Let me know if it works.

0


source


Try this: ViewDidLoad

    let backButton = UIBarButtonItem(title: "< Home", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
    navigationItem.leftBarButtonItem = backButton
    navigationItem.backBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "the_font_you_want_to_use", size: size_of_the_font_this_should_be_integer)!], forState: UIControlState.Normal)

      

and implement the following method:

    func goBack() {
    self.navigationController?.popToRootViewControllerAnimated(boolean)
}

      

Just replace the_font_you_want_to_use, size_of_the_font_this_should_be_integer and boolean with the values ​​you want and everything will work.

*** EDIT

If you don't want to go back to Root View Controller

instead

self.navigationController?.popToRootViewControllerAnimated(boolean)

      

you can say:

self.navigationController?.popViewControllerAnimated(boolean)

      

or even pop into some other ViewController

by specifying the first parameter popToViewController

as a class object YourViewController

and the second as a boolean value for animation.

0


source







All Articles