Reputation: 2809
I currently am working on an app in Swift where in my viewDidLoad() method I have purposely hidden my rightBarButton on my navigation bar like this:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(TableViewController.dismiss))
self.navigationItem.setRightBarButtonItem(nil, animated: true)
However, under certain circumstances, I would like to display the rightBarButton. How would I do this? What would be the opposite of the above line of code?
Upvotes: 1
Views: 170
Reputation: 23451
You can do one of the following two options:
Keep a reference of your UIBarButtonItem
and every time you disappear you save it to then when you want to show it again you set the old value.
Play with the color of the UIBarButtonItem
and the enabled/disable property to enable the interaction with it.
The first choice always keep a reference globally to the UIBarButtonItem
and the second need to know the exact color of the original UIBarButtonItem
to give to its original state:
First Option:
private var isHidden: Bool!
private var righBarButtonItem: UIBarButtonItem!
@IBAction func hideButton(sender: AnyObject) {
if self.isHidden == true {
self.isHidden = false
self.navigationItem.rightBarButtonItem = righBarButtonItem
}
else {
self.isHidden = true
righBarButtonItem = self.navigationItem.rightBarButtonItem
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
}
Second Option:
@IBAction func hideButton(sender: AnyObject) {
if self.isHidden == true {
self.isHidden = false
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.clearColor()
self.navigationItem.rightBarButtonItem?.enabled = false
}
else {
self.isHidden = true
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.blueColor()
self.navigationItem.rightBarButtonItem?.enabled = true
}
}
In the above examples I set a variable with the state of the UIBarButtonItem
for purposes of know the value and and @IBOutlet
to hide/show the UIBarButtonItem
. The variable isHidden
need to set it's initial value in the viewDidLoad
.
I hope this help you.
Upvotes: 2
Reputation: 5089
Once you set the bar button item to nil
, it is gone. Something you can do however, is store the bar button item like so:
let barButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(TableViewController.dismiss));
and then you can make it appear/disappear like so:
self.navigationItem.rightBarButtonItem = barButtonItem
self.navigationItem.setRightBarButtonItem(nil, animated: true)
then just access the barButtonItem
whenever you want it to appear/disappear.
Upvotes: 2