How do I hide a UIBarButtonItem?

I am trying to hide a bar button item. There is no isHidden method for a button. How do I accomplish this?

Answered by Claude31 in 403515022

Yes, I understood that was your question.


So, please show the code where you create the button.


What I did, with a right button:


In viewDidLoad:

        let rightButton = UIBarButtonItem(title: "Sa Riera", style: .plain, target: self, action: #selector(logoutUser(_ :))) // A nice name…
        self.navigationItem.rightBarButtonItem  = rightButton

Declare the Action func


    @objc func logoutUser(_ sender: UIButton) {
        print("Right Button")
    }


Then, I create a button to toggle the isHidden of the bar button, removing or recreating the button:


    @IBAction func showHideRightBarButton(_ sender: UIButton) {
        if self.navigationItem.rightBarButtonItem == nil {
            let rightButton = UIBarButtonItem(title: "Sa Riera", style: .plain, target: self, action: #selector(logoutUser(_ :)))
            self.navigationItem.rightBarButtonItem  = rightButton
        } else {
            self.navigationItem.setRightBarButton(nil, animated: true)
        }
    }

Did you try:


self.navigationItem.setHidesBackButton(true, animated:true)

That hides the back button. I am trying to hide a different button that I created in the navigation bar.

Accepted Answer

Yes, I understood that was your question.


So, please show the code where you create the button.


What I did, with a right button:


In viewDidLoad:

        let rightButton = UIBarButtonItem(title: "Sa Riera", style: .plain, target: self, action: #selector(logoutUser(_ :))) // A nice name…
        self.navigationItem.rightBarButtonItem  = rightButton

Declare the Action func


    @objc func logoutUser(_ sender: UIButton) {
        print("Right Button")
    }


Then, I create a button to toggle the isHidden of the bar button, removing or recreating the button:


    @IBAction func showHideRightBarButton(_ sender: UIButton) {
        if self.navigationItem.rightBarButtonItem == nil {
            let rightButton = UIBarButtonItem(title: "Sa Riera", style: .plain, target: self, action: #selector(logoutUser(_ :)))
            self.navigationItem.rightBarButtonItem  = rightButton
        } else {
            self.navigationItem.setRightBarButton(nil, animated: true)
        }
    }

Yes this worked. I had to add it in viewWillAppear though.

<UIBarButtonItem Reference>.setValue(true, forKey: "hidden")

How do I hide a UIBarButtonItem?
 
 
Q