gpt4 book ai didi

swift - 更改导航项标题

转载 作者:行者123 更新时间:2023-11-30 11:16:58 25 4
gpt4 key购买 nike

我正在尝试更改 Product 中的标题,但不知何故 navigationItem 有所不同。为什么 Container 中的 navigationItemProduct 中的不一样?

class VC1: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let controller = Container()
let navigation = UINavigationController(rootViewController: controller)

navigationController?.pushViewController(navigation, animated: true)
}
}

class Container: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

print(navigationItem)
navigationItem.title = "test"

let controller = Product()

controller.didMove(toParentViewController: self)
self.addChildViewController(controller)

view.addSubview(controller.view)
}
}

class Product: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

print(navigationItem)
navigationItem.title = "" // Doesn't remove the title
}
}

最佳答案

我正在阅读 navigationItem 的文档,它是这样说的:

This is a unique instance of UINavigationItem created to represent the view controller when it is pushed onto a navigation controller.

但是,在您的情况下,嵌入式 VC 不是导航 Controller 的直接子级。

所以,我尝试了以下代码并且它有效。关键部分是,如果存在父 View Controller ,我会重写 navigationItem 以返回父级的导航项。

override var navigationItem: UINavigationItem {
if let parentItem = parent?.navigationItem {
return parentItem
} else {
return super.navigationItem
}
}

关于swift - 更改导航项标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652800/

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