How to hide a bar button item for certain users

和自甴很熟 提交于 2019-11-27 03:51:28

问题


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?


回答1:


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
}



回答2:


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.




回答3:


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:


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))


来源:https://stackoverflow.com/questions/27887218/how-to-hide-a-bar-button-item-for-certain-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!