首页 > 解决方案 > 如何以编程方式呈现带有导航栏的 ViewController?

问题描述

当以这种方式呈现我的视图控制器时,我没有得到导航栏,即使视图控制器嵌入在界面构建器的导航控制器中。

        if let stockVC = storyboard?.instantiateViewController(withIdentifier: "Stock") as? StockTableViewController {
        stockVC.stockToDisplay = commonData.stock.filter { $0.productID.contains(product) }
        // No NavigationBar with this one
        navigationController?.present(stockVC, animated: true)
        // No NavigationBar with this one
        self.present(stockVC, animated: true)
    }

我知道导航栏有效,因为如果我在情节提要中将 ViewController 设置为初始值,它会显示。

我在这里做错了什么?

标签: iosswiftxcode

解决方案


当您呈现视图控制器时,它不是当前导航堆栈的一部分。您需要创建一个包含您的 stockVC 的新导航控制器,并显示新的导航控制器:

if let stockVC = storyboard?.instantiateViewController(withIdentifier: "Stock") as? StockTableViewController {
    stockVC.stockToDisplay = commonData.stock.filter { $0.productID.contains(product) }
    let stockNavigationController = UINavigationController(rootViewController: stockVC)
    self.present(stockNavigationController, animated: true)
}

推荐阅读