How to hide a bar button item for certain users

grabury picture grabury · Jan 11, 2015 · Viewed 22.4k times · Source

I have a settings bar button item (set as left bar button item). I only want to display it if the user is logged in.

I thought I could use the following for anonymous users

navigationItem.leftBarButtonItem = nil

But then how would I show it as soon as they logged in?

Answer

rakeshbs picture rakeshbs · Jan 11, 2015

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

var leftBarButtonItem : UIBarButtonItem!

Inside viewDidLoad:

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

In logic:

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