I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the button. So far I have,
var addButton: UIBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))
override func viewDidLoad() {
super.viewDidLoad()
let boool = true
if boool {
self.navigationItem.rightBarButtonItem = self.addButton
}
else {
self.navigationItem.rightBarButtonItem = nil
}
}
func addTapped(sender: AnyObject) {
print("hjxdbsdhjbv")
}
I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.
Firstly, you need to connect you navigation bar to an IBOutlet so that you can refer to it in your code. After that, this code should work:
You say you added a
UINavigationBar
to your view controller via storyboard, but looking at the code you provided there is no outlet connection to your navigation bar in IB.In order to access
self.navigationItem
your view controller must be embedded in aUINavigationController
or be part of a hierarchy which is. Unless you have a need for a custom navigation bar on an individual view controller, I suggest removing that from Interface Builder, then making sure either the view controller in question is embedded in aUINavigationController
or it is being pushed onto the navigation stack from another controller which is embedded in a navigation controller and then you should see yourUIBarButtonItem
.It’s simple. Put this line of code to the
viewDidLoad
: