8

So I'm trying to change the left nav bar button item in viewWillAppear (the item needs to be changed back and forth, so viewDidLoad won't work). I have the following code in viewWillAppear:

        // There is a diff 'left bar button item' defined in storyboard. I'm trying to replace it with this new one
        var refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: {})
        self.navigationController.navigationItem.leftBarButtonItem = refreshButton
        // title and color of nav bar can be successfully changed
        self.navigationController.navigationBar.barTintColor = UIColor.greenColor()
        self.title = "Search result"

I used debugger to make sure every line is executed. But the 'leftBarButtonItem' wasn't updated. nav bar stuff however got updated successfully. I'm out of moves now. Ideas? Thanks!

Wei Wei
  • 91
  • 1
  • 1
  • 6

1 Answers1

31

The following code should work:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
        navigationItem.leftBarButtonItem = refreshButton

        navigationController?.navigationBar.barTintColor = UIColor.greenColor()
        title = "Search result"
    }

    func buttonMethod() {
        print("Perform action")
    }

}

If you really need to perform it in viewWillAppear:, here is the code:

import UIKit

class ViewController: UIViewController {

    var isLoaded = false

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        if !isLoaded {
            let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
            navigationItem.leftBarButtonItem = refreshButton
            isLoaded = true

            navigationController?.navigationBar.barTintColor = UIColor.greenColor()
            title = "Search result"
        }
    }

    func buttonMethod() {
        print("Perform action")
    }

}

You can learn more about the navigationItem properties with this previous question.

Community
  • 1
  • 1
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
  • You just hit the nail on the head. 'navigationItem.leftBarButtonItem' is the way to go. Thanks a lot! – Wei Wei Sep 08 '14 at 16:47
  • You probably don't want to do this in `viewWillAppear`, it will be called every time the VC gets presented - something like `viewDidLoad` would be better fit. – Zorayr Mar 28 '15 at 05:18
  • @Zorayr: You're totally right. The question mentioned `viewWillAppear` but `viewDidLoad` is definitely a better place for this code. Code updated. – Imanou Petit Mar 28 '15 at 10:40
  • Work fine. Thank you. – Duque Jan 19 '17 at 16:38