使用Swift编程在程序中动态更改导航栏项目

8

我想在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个回答

31
以下代码应该可以工作:
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")
    }

}

你可以通过这个之前的问题了解更多关于navigationItem属性的信息。


你说得一点也没错。'navigationItem.leftBarButtonItem' 是正确的方法。非常感谢! - Wei Wei
你可能不想在 viewWillAppear 中执行此操作,因为每次 VC 被呈现时都会调用它 - 使用类似 viewDidLoad 的方法会更好。 - Zorayr
@Zorayr:你说得对。问题提到了viewWillAppear,但是viewDidLoad绝对是更好的位置放置这段代码。代码已更新。 - Imanou Petit
正常工作。谢谢。 - Duque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接