7

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!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You just hit the nail on the head. 'navigationItem.leftBarButtonItem' is the way to go. Thanks a lot!
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: You're totally right. The question mentioned viewWillAppear but viewDidLoad is definitely a better place for this code. Code updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.