4

How to to set action backBarButtonItem and still display left arrow?

I used this code but the arrow was not display

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

but when I used this code the action not working

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

Thanks

Aditya Dharma
  • 708
  • 2
  • 8
  • 22

3 Answers3

2

As an alternative to setting an action, you can keep the backBarButtonItem and use isMovingFromParentViewController instead to handle logic for moving back on the navigation stack.

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if isMovingFromParentViewController() {
        .. do something here
    }
}
David James
  • 2,430
  • 1
  • 26
  • 35
0

Try this

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

Let me know if it works.

Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29
  • It seems like my code. Please read my question carefully. thanks – Aditya Dharma Oct 19 '14 at 04:06
  • Actually it is kinda different because you are using the top item property of the navigation bar of the navigation controller which might not always be active such as when the page is not embedded in a navigation controller. I am, on the other hand, using the leftBarButtonItem of the page's navigationItem. Please try my code and see if it works because I tried it before posting the answer – Rajeev Bhatia Oct 19 '14 at 14:18
  • The only thing common between our codes is the initialisation of the barbuttonitem – Rajeev Bhatia Oct 19 '14 at 14:18
0

Try this: In 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 the_font_you_want_to_use, size_of_the_font_this_should_be_integer and boolean with the values you want, and everything will be working.

*** EDIT

If you don't want to get back to Root View Controller, instead of

self.navigationController?.popToRootViewControllerAnimated(boolean)

you can say:

self.navigationController?.popViewControllerAnimated(boolean)

or even pop to some other ViewController with specifying the first parameter of the popToViewController to be the object of YourViewController class, and second the boolean value for animation.

Dragos Strugar
  • 1,314
  • 3
  • 12
  • 30