一尘不染

使用快速iOS使UIBarButtonItem消失

swift

我有一个从故事板链接到的IBOutlet

@IBOutlet var creeLigueBouton: UIBarButtonItem!

如果条件成立,我想使其消失

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

阅读 184

收藏
2020-07-07

共1个答案

一尘不染

您真的要隐藏/显示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")
    }

}
2020-07-07