我有一个我从故事板链接到的IBOutlet
@IBOutlet var creeLigueBouton: UIBarButtonItem!
如果条件成立,我想让它消失
if(condition == true) { // Make it disappear }
你真的想隐藏/展示creeLigueBouton吗?相反,启用/禁用UIBarButtonItems要容易得多。您可以使用以下几行来完成此操作:
if(condition == true) { creeLigueBouton.enabled = false } else { creeLigueBouton.enabled = true }
这段代码甚至可以用更短的方式重写:
creeLigueBouton.enabled = !creeLigueBouton.enabled
让我们在UIViewController子类中看到它:
import UIKit class ViewController: UIViewController { @IBOutlet weak var creeLigueBouton: UIBarButtonItem! @IBAction func hide(sender: AnyObject) { creeLigueBouton.enabled = !creeLigueBouton.enabled } }
如果您真的想显示/隐藏creeLigueBouton,可以使用以下代码:
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") } }