Make a UIBarButtonItem disappear using swift IOS

2019-01-26 02:44发布

问题:

I have an IBOutlet that I have linked to from the storyboard

@IBOutlet var creeLigueBouton: UIBarButtonItem!

and I want to make it disappear if a condition is true

if(condition == true)
{
    // Make it disappear
}

回答1:

Do you really want to hide/show creeLigueBouton? It is instead much easier to enable/disable your UIBarButtonItems. You would do this with a few lines:

if(condition == true) {
    creeLigueBouton.enabled = false
} else {
    creeLigueBouton.enabled = true
}

This code can even be rewritten in a shorter way:

creeLigueBouton.enabled = !creeLigueBouton.enabled

Let's see it in a UIViewController subclass:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var creeLigueBouton: UIBarButtonItem!

    @IBAction func hide(sender: AnyObject) {
        creeLigueBouton.enabled = !creeLigueBouton.enabled
    }

}

If you really want to show/hide creeLigueBouton, you can use the following code:

import UIKit

class ViewController: UIViewController {

    var condition: Bool = true
    var creeLigueBouton: UIBarButtonItem! //Don't create an IBOutlet

    @IBAction func hide(sender: AnyObject) {
        if(condition == true) {
            navigationItem.rightBarButtonItems = []
            condition = false
        } else {
            navigationItem.rightBarButtonItems = [creeLigueBouton]
            condition = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        creeLigueBouton = UIBarButtonItem(title: "Creer", style: UIBarButtonItemStyle.Plain, target: self, action: "creerButtonMethod")
        navigationItem.rightBarButtonItems = [creeLigueBouton]
    }

    func creerButtonMethod() {
        print("Bonjour")
    }

}


回答2:

Use the property enabled and tintColor

    let barButtonItem:UIBarButtonItem? = nil

    if isHidden{
        barButtonItem?.enabled      = false
        barButtonItem?.tintColor    = UIColor.clearColor()
    }else{
        barButtonItem?.enabled      = true
        barButtonItem?.tintColor    = nil
    }


回答3:

// Nice answer haiLong, I think as an extension this is more convenient.

extension UIBarButtonItem {
    var isHidden: Bool {
        get {
            return !isEnabled && tintColor == .clear
        }
        set {
            tintColor = newValue ? .clear : nil
            isEnabled = !newValue
        }
    }
}

EDIT: Removed forced unwrapping and fixed enabled value.



回答4:

For Swift 3

if (Show_condition) {
  self.navigationItem.rightBarButtonItem = self.addAsset_btn
 }
else {
  self.navigationItem.rightBarButtonItem = nil
 }


回答5:

First way:

Just set .title to ""

Second way:

Just call updateToolBar() whenever you want to show/hide the creeLigueBouton.

func updateToolBar() {
    var barItems: [UIBarButtonItem] = []

    if condition != true {
        // Make it appear
        barItems.append(creeLigueBouton)
    }

    barItems.append(anotherButton)

    myToolBar.setItems(barItems, animated: true)

    myToolBar.setNeedsLayout()
}


回答6:

heres my solution:

hide:

self.creeLigueBouton.title = ""
self.creeLigueBouton.style = UIBarButtonItemStyle.Plain
self.creeLigueBouton.enabled = false

show:

self.creeLigueBouton.title = "Original Button Text"
self.creeLigueBouton.style = UIBarButtonItemStyle.Bordered
self.creeLigueBouton.enabled = true


回答7:

The following solution works for me.

        var skipButton: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    skipButton.frame = CGRectMake(10.0, 0.0, 58.0, 32.0);
    skipButton.setTitle("Skip", forState: UIControlState.Normal)
    skipButton.setTitleColor(UIColor(red: 0.0, green: 122.0/255.0, blue: 255.0/255.0, alpha: 1.0), forState: UIControlState.Normal)
    skipButton.addTarget(self, action: "rightButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    var skipButtonItem = UIBarButtonItem(customView: skipButton)
    self.navigationItem.rightBarButtonItem = skipButtonItem;

    if hideSkipButton == true {
        self.navigationItem.rightBarButtonItem = nil
    } 


回答8:

If you have set of UIBarButtonItems to hide, e.g. only show them on Landscape orientation, and hide or Portrait, you can use tag and Swift Array's filter. Let's assume we made @IBOutlet link to UIToolBar:

@IBOutlet weak var toolbar: UIToolbar!

First, we save toolbar's items in viewDidLoad:

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.
  toolbarItems = toolbar.items
}

Set the tag property of UIBarButtonItem you want to show on Landscape orientation to 1 or whatever you like. Then, override func traitCollectionDidChange

override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    switch (traitCollection.horizontalSizeClass, traitCollection.verticalSizeClass) {
    case (.Compact, .Regular): // iPhone Portrait
      let items: [UIBarButtonItem]?
      if view.frame.width > 320 { // iPhone 6 & 6S
        items = toolbarItems?.filter({ $0.tag < 5 })
      } else { 
        items = toolbarItems?.filter({ $0.tag < 4 })
      }
      bottomToolbar.setItems(items, animated: true)
    case (_, .Compact): // iPhone Landscape
      let items = toolbarItems?.filter({ $0.tag < 6 })
      bottomToolbar.setItems(items, animated: true)
    default: // iPad
      break
    }
  }

In this example, I set all UIBarButtonItem's tag for iPad only to 6, iPhone Landscape to 5, and for iPhone 6 & 6+ to 4.



回答9:

You can use text attributes to hide a bar button:

barButton.enabled = false
barButton.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clearColor()], forState: .Normal)

Also I've made extension for UIBarButtonItem with a hidden property:

extension UIBarButtonItem {

    var titleTextAttributes: [NSObject : AnyObject]! {
        set {
            setTitleTextAttributes(newValue, forState: .Normal)
        }

        get {
            return titleTextAttributesForState(.Normal)
        }

    }

    private static var savedAttributesKey = "savedAttributes"

    var savedAttributes: [NSObject : AnyObject]? {
        set {
            objc_setAssociatedObject(self, &UIBarButtonItem.savedAttributesKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        }
        get {
            return objc_getAssociatedObject(self, &UIBarButtonItem.savedAttributesKey) as? [NSObject : AnyObject]
        }
    }

    var hidden: Bool {
        set {
            enabled = !newValue

            if newValue {
                savedAttributes = titleTextAttributes

                // Set a clear text color
                var attributes = titleTextAttributes
                attributes[NSForegroundColorAttributeName] = UIColor.clearColor()
                titleTextAttributes = attributes
            }
            else {
                titleTextAttributes = savedAttributes
            }
        }

        get {
            return enabled
        }
    }
}


回答10:

Try this. (Make newbackbutton global variable)

override func viewDidLoad() {

    let newBackButton = UIBarButtonItem()

     newBackButton.title = " << Return to Gallery"
    newBackButton.style  = UIBarButtonItemStyle.Done
    newBackButton.target = self
    newBackButton.action = "backtoScoutDetail:"
    self.navigationItem.rightBarButtonItem = newBackButton

}

override func viewWillAppear(animated: Bool) {

    newBackButton.title = ""
    self.navigationItem.rightBarButtonItem = newBackButton        

     }


回答11:

I did it using this:

navigationItem.setHidesBackButton(true, animated: true)


回答12:

I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me (Using Swift3).

func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}


回答13:

It is quite late to reply but looking for an answer for my problem I found this topic. The marked answer did not help me, but I managed to solve my problem thanks to @haiLong's answer. My solution works for all types of bar buttons... I think. Add this to your ViewController and use as needed.

var tintColorsOfBarButtons = [UIBarButtonItem: UIColor]()

    func hideUIBarButtonItem(button: UIBarButtonItem) {
        if button.tintColor != UIColor.clear {
            tintColorsOfBarButtons[button] = button.tintColor
            button.tintColor = UIColor.clear
            button.isEnabled = false
        }
    }

    func showUIBarButtonItem(button: UIBarButtonItem) {
        if tintColorsOfBarButtons[button] != nil {
            button.tintColor = tintColorsOfBarButtons[button]
        }
        button.isEnabled = true
    }

I hope it saves some time to other developers :)



回答14:

I had the same problem with a tool bar that I had to hide and show its last button. So I declared a var to hold the UIBarButtonItem and removed it from the bar or added depending on the situation like:

inside the class declared the var and linked the toolbar:

var buttonToHide : UIBarButtonItem?

@IBOutlet weak var toolbarOne: UIToolbar!

at the viewDidLoad :

buttonToHide = toolbarOne.items![toolbarOne.items!.count - 1] as? UIBarButtonItem

in my code I made the trick:

if situationOccurrsToHide {
   toolbarOne.items!.removeLast()
}

or

if situationOccursToShow 
{    
   toolbarOne.items!.append(buttonToHide!) 
}

You can use the removeAtIndex or insert(buttonToHide, atIndex: xx) to remove or reinsert the button at a specific position.

You must be careful not to insert or remove the button more than once.

Hope it helps.



回答15:

Try these:

 self.navigationController?.navigationBar.backItem?.title = ""
        navigationItem.backBarButtonItem?.title = ""
        navigationItem.leftBarButtonItem?.title = ""
navigationItem.hidesBackButton = true


        navigationItem.setLeftBarButtonItem(nil, animated: true)
        navigationItem.setRightBarButtonItem(nil, animated: true)