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
    }
}

最佳答案

不要设置导航控制器的navigationItem。在视图控制器上设置。导航控制器显示堆栈中俯视控制器的导航项。
所以这句话:

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

应该是:
controller.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

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

关于swift - 不同的NavigationItem,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51461099/

10-13 04:56