How to hide a bar button item for certain users

4 Solutions Collect From Internet About “How to hide a bar button item for certain users”

You can store a copy of the leftBarButtonItem in a strong property and set it back after the users log in.

var leftBarButtonItem : UIBarButtonItem!

Inside viewDidLoad

self.leftBarButtonItem = UIBarButtonItem(title: "test", style:         UIBarButtonItemStyle.Plain, target: nil, action: nil)

In logic

if loggedIn
{
    self.navigationItem.leftBarButtonItem = self.leftBarButtonItem
}
else
{
    self.navigationItem.leftBarButtonItem = nil
}

Best Way is just custom your Bar buttom with image. Set barbuttom.image = nil to Hide again assign the image to show. And dont forget to make the barbutton isEnabled as false.

I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me.

func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}

if you want to hide/show UIBarButtonItem : For Swift 3

Used below simple code :

Declaration :

var doneButton = UIBarButtonItem()

In ViewDidLoad() or ViewWillAppear() or where you want to hide it : [hide bar button]

self.navigationItem.rightBarButtonItem = nil

where you want to show bar button : [use anywhere in your code]

self.navigationItem.rightBarButtonItem = self.doneButton
        doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.dismissPicker))