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!
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.
To change a navigation bar color in SwiftUI, you apply toolbarBackground modifier to the content view of NavigationStack .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With