在Swift中以编程方式更改导航栏项目

时间:2014-09-08 05:36:59

标签: swift

所以我正在尝试更改viewWillAppear中的左侧导航栏按钮项(该项需要来回更改,因此viewDidLoad不起作用)。我在viewWillAppear中有以下代码:

        // There is a diff 'left bar button item' defined in storyboard. I'm trying to replace it with this new one
        var refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: {})
        self.navigationController.navigationItem.leftBarButtonItem = refreshButton
        // title and color of nav bar can be successfully changed
        self.navigationController.navigationBar.barTintColor = UIColor.greenColor()
        self.title = "Search result"

我使用调试器来确保每一行都被执行。但是'leftBarButtonItem'没有更新。导航栏的东西,但成功更新。我现在没有动作了。想法?谢谢!

1 个答案:

答案 0 :(得分:29)

以下代码应该有效:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
        navigationItem.leftBarButtonItem = refreshButton

        navigationController?.navigationBar.barTintColor = UIColor.greenColor()
        title = "Search result"
    }

    func buttonMethod() {
        print("Perform action")
    }

}

如果您确实需要在viewWillAppear:中执行,请输入以下代码:

import UIKit

class ViewController: UIViewController {

    var isLoaded = false

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        if !isLoaded {
            let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "buttonMethod")
            navigationItem.leftBarButtonItem = refreshButton
            isLoaded = true

            navigationController?.navigationBar.barTintColor = UIColor.greenColor()
            title = "Search result"
        }
    }

    func buttonMethod() {
        print("Perform action")
    }

}

您可以使用this previous question详细了解navigationItem属性。