不同的NavigationItem

时间:2018-07-22 00:31:18

标签: swift uinavigationbar

VC1嵌入在NavigationController中。在VC1中,我将设置一个新的VC2并将其嵌入到一个新的NavigationController中。我想在设置VC2时添加一个按钮,以便访问navigationItem,但是该按钮没有显示。我已经检查了navigationItemVC1中的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
    }
}

1 个答案:

答案 0 :(得分:0)

请勿设置导航控制器的navigationItem。在视图控制器上进行设置。导航控制器在其堆栈中显示来自顶视图控制器的导航项。

所以这行:

navigation.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

应为:

controller.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

除此之外,您的打印陈述是正确的。在VC1中,打印导航控制器的导航项。由于VC2是顶视图控制器,它将显示VC2的导航项。