更改 NavigationItem 标题
Changing NavigationItem title
我正在尝试更改 Product
中的标题,但不知何故 navigationItem
有所不同。为什么 Container
中的 navigationItem
与 Product
中的不同?
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 不是导航控制器的直接子项。
因此,我尝试了以下代码并且它有效。关键部分是如果有父视图控制器,我将 navigationItem
覆盖到 return 父导航项。
override var navigationItem: UINavigationItem {
if let parentItem = parent?.navigationItem {
return parentItem
} else {
return super.navigationItem
}
}
我正在尝试更改 Product
中的标题,但不知何故 navigationItem
有所不同。为什么 Container
中的 navigationItem
与 Product
中的不同?
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 不是导航控制器的直接子项。
因此,我尝试了以下代码并且它有效。关键部分是如果有父视图控制器,我将 navigationItem
覆盖到 return 父导航项。
override var navigationItem: UINavigationItem {
if let parentItem = parent?.navigationItem {
return parentItem
} else {
return super.navigationItem
}
}