Wei Wei
Wei Wei

Reputation: 111

changing nav bar item programmatically in Swift

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!

Upvotes: 8

Views: 27014

Answers (1)

Imanou Petit
Imanou Petit

Reputation: 92419

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.

Upvotes: 31

Related Questions