如何以编程方式将ViewController与Navigationbar一起呈现



当以这种方式呈现我的视图控制器时,即使视图控制器嵌入在界面生成器中的导航控制器中,我也不会得到导航栏。

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设置为初始值,它就会显示出来。

我在这里做错了什么?

当您呈现一个视图控制器时,它不是当前导航堆栈的一部分。您需要创建一个新的导航控制器,其中包含您的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)
}

最新更新