Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing nav bar item programmatically in Swift

Tags:

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!

like image 431
Wei Wei Avatar asked Sep 08 '14 05:09

Wei Wei


People also ask

How do I customize the navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.

How do I change the navigation bar title color in SwiftUI?

To change a navigation bar color in SwiftUI, you apply toolbarBackground modifier to the content view of NavigationStack .


1 Answers

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.

like image 166
Imanou Petit Avatar answered Sep 19 '22 13:09

Imanou Petit