I need to hide the right button in the Navigation Bar, then unhide it after the user selects some options.
Unfortunately, the following doesn\'t work:
For Swift 3
if let button = self.navigationItem.rightBarButtonItem {
button.isEnabled = false
button.tintColor = UIColor.clear
}`
To hide:
if let topItem = self.navigationController?.navigationBar.topItem {
topItem.rightBarButtonItem = nil
}
If you have only one bar button item in the right side you can use this one,
self.navigationItem.rightBarButtonItem = nil;
Suppose if you have multiple bar button in the right side, for example suppose you have two bar button items(search button and filter button) in the right side of your navigation item. Now the right bar button items are
self.navigationItem.rightBarButtonItems = [searchItem,filterItem]
and you have to hide only search button, you can use like,
self.navigationItem.rightBarButtonItems = [filterItem]
Now what happening is, you can completely hide the search button from the navigation item and the filter item comes in the place of search item
In swift 4 I has a trick to show / hide right or left button:
Step 1: Create a IBOutlet button in view controller:
@IBOutlet var navigationItemButton: UIBarButtonItem!
Step 2: Create Hide button function:
func hideNavigationButton() {
navigationItemButton.isEnabled = false
navigationItemButton.tintColor = UIColor.clear
}
Step 3: Create Show button function:
func showNavigationButton() {
navigationItemButton.isEnabled = true
navigationItemButton.tintColor = UIColor.white
}
Step 4: Just call the functions that you want, use hideNavigationButton()
to hide, and showNavigationButton()
to show the button.
Regards!
SWIFT 2.2
In swift 2.2 self.navigationItem does not work. Instead create an outlet of the NavigationItem (I named it below "nav") and use it.
Also the following suggestion did not work for me using Xcode 7.3 and swift 2.2
nav.leftBarButtonItem?.customView?.hidden = true
So I used the idea of @Matt J above as follows (I have 2 items on the left):
Create outlets for the items in the navigation bar and variables to store them
@IBOutlet weak var settingItem: UIBarButtonItem!
@IBOutlet weak var logoItem: UIBarButtonItem!
var sav_settingItem: UIBarButtonItem = UIBarButtonItem()
var sav_logoItem: UIBarButtonItem = UIBarButtonItem()
Save the items in viewDidLoad()
sav_settingItem = nav.leftBarButtonItems![0]
sav_logoItem = nav.leftBarButtonItems![1]
To HIDE set them to nil
nav.leftBarButtonItem = nil
nav.leftBarButtonItem = nil
To SHOW them
if (nav.leftBarButtonItem == nil) {
nav.leftBarButtonItem = sav_settingItem
nav.leftBarButtonItems?.append(sav_logoItem)
return
}
You can use below code:
self.navigationItem.rightBarButtonItem?.image = nil
self.navigationItem.rightBarButtonItem?.isEnabled = false