Show or hide UIBarButtonItem in UIToolbar programmatically

4 Solutions Collect From Internet About “Show or hide UIBarButtonItem in UIToolbar programmatically”

This answer is inspired by this answer.

I will improve on it and make all the work programmatically. No need to update/set the class of the UIBarButtonItem instance to use the new subclass anymore.

We could just add isHidden attribute to the UIBarButtonItem. Then just use it as you want.

extension UIBarButtonItem {
   var isHidden: Bool = false {
      didSet {
          isEnabled = !isHidden
          tintColor = isHidden ? UIColor.clear : UIColor.black
      }
   }
}

In your case, after you add the extension (outside any class). You could use it as:

self.toolbar.items.indexOf(1).isHidden = true

UIBarButton does not have a “hidden” property so you cannot hide. You can remove it. Since you only have one button on the toolbar, you can clear all the items on the toolbar.

toolBar.setItems([], animated: true)

If you wanted to remove a specific item, you can use the index.

    var items = toolBar.items
    items?.removeAtIndex(0)
    toolBar.setItems(items, animated: true)

Looks like it’s a ‘next’ button, the standard way to handle when there is nothing to move to next is to simply disable it like this:

nextBarButton.enabled = NO;

The icon is greyed out automatically too.

You can add simple function, for hiding state

extension UIBarButtonItem {
    func set(hide: Bool) {
        isEnabled = !hide
        tintColor = hide ? .clear : .white
    }
}