VC1
嵌入在NavigationController
中。在VC1
中,我将设置一个新的VC2
并将其嵌入到一个新的NavigationController
中。我想在设置VC2
时添加一个按钮,以便访问navigationItem
,但是该按钮没有显示。我已经检查了navigationItem
和VC1
中的VC2
,它们具有相同的内存地址。我在做什么错了?
class VC1: UIViewController {
let button = UIButton()
func changeView() {
let controller = VC2()
let navigation = UINavigationController(rootViewController: controller)
button.sizeToFit()
navigation.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
print("VC1: ", Unmanaged.passUnretained(navigation.navigationItem))
navigationController?.pushViewController(navigation, animated: true)
}
}
class VC2: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super. viewDidAppear(animated)
print("VC2: ", Unmanaged.passUnretained(navigationItem)) // same memory
}
}
答案 0 :(得分:0)
请勿设置导航控制器的navigationItem
。在视图控制器上进行设置。导航控制器在其堆栈中显示来自顶视图控制器的导航项。
所以这行:
navigation.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
应为:
controller.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
除此之外,您的打印陈述是正确的。在VC1
中,打印导航控制器的导航项。由于VC2
是顶视图控制器,它将显示VC2
的导航项。