How to hide a bar button item for certain users

2019-01-19 11:02发布

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?

4条回答
做自己的国王
2楼-- · 2019-01-19 11:39

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))
查看更多
smile是对你的礼貌
3楼-- · 2019-01-19 11:40

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
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-19 11:43

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-01-19 12:03

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
}
查看更多
登录 后发表回答