2017-06-17 8 views
1

前に取得したいviewController私はメニューが第二UIViewControllerに移動し開かれた場所からのUIViewControllerを取得したいnavigationメニューから任意の行を選択した場合前のUIViewControllerを取得する

は、私が2 UIViewControllersnavigationMenuを持っています。

私はこれを試してみましたが、nilを返す数えるこの場合

の前のUIViewControllerを取得する方法を知りたい:

let n: Int! = self.navigationController?.viewControllers.count 
print(n) 
let myUIViewController = self.navigationController?.viewControllers[n-2] as! UIViewController 

編集: -

オープニングメニューコード

let menuButton = UIBarButtonItem.init(title :"open", style: .plain, target: self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:))) 
    navigationItem.leftBarButtonItem = menuButton 
+0

このライブラリあなたはメニューのために使用していますか? –

+0

SWRevealViewController –

+0

あなたは一箇所でしか知りませんが、任意のファイルから知りたいですか? –

答えて

0

を使用し、私はあなたの場合、私はどこにでも

+0

@ Rashwan Lこれは私の答えです –

3

これは、以前のを取得する方法です、説明のコメントを確認してください。

// get all the viewControllers to start with 
if let controllers = self.navigationController?.viewControllers { 
    // iterate through all the viewControllers 
    for (index, controller) in controllers.enumerated() { 
     // when you find your current viewController 
     if controller == self { 
      // then you can get index - 1 in the viewControllers array to get the previous one 
      let myUIViewController = controllers[index-1] 
      print(controllers[index-1]) 
     } 
    } 
} 
+0

私はこの方法でメニューを開きます let menuButton = UIBarButtonItem.init(title: "open"、style:.plpl、 target:self.revealViewController()、action: #content(SWRevealViewController.revealToggle(_ :)) navigationItem.leftBarButtonItem = menuButton ナビゲーションコントローラがthatsを使用してcountがnilを返し、コードを試しても何も印刷しない場合 –

+0

これは良い答えですが、この場合助けてください(私を助けた方法) –

1

変数を2番目のViewControllerに追加します。

class SecondViewController : UIViewController 
{ 
    var previousVC = FirstViewController() 
} 

最初のViewControllerからsegueから2番目のViewControllerを実行します。

performSegue(withIdentifier: "to2nd", sender: self) //to2nd or Your Choice 

segue関数を準備するには、First View Controllerオブジェクトをターゲットに配置します。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
{ 
     if segue.identifier == "to2nd" // Or you segue id name 
     { 
      if let target = segue.destination as? SecondViewController 
      { 
       target.previousVC = self 
      } 
     } 
} 

そして今、あなたが以前のViewControllerまたはそのデータを必要なときに、previousVC

+0

編集ポストを参照してください 私はsegueのために準備を使用しない私はUIViewControllerをどこにオープンしたいのですか –

+0

この行を客観的に書く方法を知っていますかvar previousVC = FirstViewController() –

1

からもアクセスできるようにメニューがデリゲートで開かれた場所からのUIViewControllerを保存することで、私の問題を解決しましたViewControllerがNavigationControllerに組み込まれている場合、2番目のVCで標準のpopViewController関数を使用できます。

_ = navigationController?.popViewController(animated: true) 
関連する問題