gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:45:48 27 4
gpt4 key购买 nike

所以我正在尝试更改 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”没有更新。然而,导航栏的内容已成功更新。我现在没 Action 了。想法?谢谢!

最佳答案

下面的代码应该可以工作:

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 属性的更多信息.

关于swift - 在 Swift 中以编程方式更改导航栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25718004/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com