所以我正在尝试更改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'没有更新。导航栏的东西,但成功更新。我现在没有动作了。想法?谢谢!
答案 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
属性。