我想創建一個導航層次結構,我想使用 NavigationController 從 FirstViewController 轉到 SecondViewController。FirstViewController 包含我打算用來轉到 SecondViewController 的按鈕 B。我正在使用導航控制器的概念,因為我想稍后回傳 FirstViewController。我已經完成了以下步驟來實作它:
- 我已將 NavigationController 嵌入到包含 FirstViewController 和 SecondViewController 的情節提要 X 中。
- 我已經創建了一個從 FirstView 中的按鈕 B(具有與其關聯的 FirstViewController)到 SecondView(具有 SecondViewController)的轉場。
- 在展示了 firstViewController 之后,我將 navigationViewController nvc 設定如下:
nvc = UINavigationController.init(rootViewController: firstViewController)
- 稍后,當按鈕 B 被按下時,我執行以下代碼將 secondViewController 推送到導航層次結構中:
self.nvc?.pushViewController(secondViewController, animated: true)
但是,即使在推送之后, secondView 也不會出現。
- 我已將按鈕 B 和 secondViewController 之間的 segue 命名為 kSegue,因此我嘗試將 segue 作為附加項執行,以查看 secondViewController 是否出現:
self.performSegue(withIdentifier: "kSegue", sender: self)
當第 4 步和第 5 步同時執行時會發生例外。例外表明我正在推送導航層次結構中已經存在的 viewController,但是即使我注釋 performSegue 代碼,第二個視圖仍然沒有打開。
請問我在這里犯了什么錯誤?
uj5u.com熱心網友回復:
在情節提要中,確保從導航控制器到第一個視圖控制器有一個 rootViewController segue。另外,確保導航控制器被標記為初始視圖控制器。
在代碼中,更改
self.nvc?.pushViewController...
到
self.navigationController?.pushViewController...
uj5u.com熱心網友回復:
1) Take a navigation controller on your storyboard
2) Set navigation controller as initial view controller
3) set view controller A as a root view controller of your navigation controller
4) in "GoToB" method access View controller B's instance and push it in navigation controller
5) On View controller B's "Go Back" method write code to pop it.
6) Dont forget to set storyboard Id on both A & B view controller

class FirstViewController: UIViewController
{
lazy var secondViewController : SecondViewController? =
{
let secondViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
return secondViewController
}()
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func goToB(sender : UIButton)
{
guard let secondViewController = self.secondViewController else
{
return
}
self.navigationController?.pushViewController(secondViewController, animated: true)
}
}
class SecondViewController: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func goBack(sender : UIButton)
{
self.navigationController?.popViewController(animated: true)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459933.html
