2017-06-17 42 views
1

我想先前得到viewController獲取以前的UIViewController swift

我有2 UIViewControllersnavigationMenu當我選擇從navigation菜單我想從那裏菜單中打開移動到第二UIViewController得到的UIViewController任何行。

我想知道如何在這種情況下

我想這讓以前UIViewController但算上返回nil

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

我解決我的問題,從節約的UIViewController其中代表打開的菜單中,所以我可以從任何地方

+0

@Rashwan L這是我的答案 –

3

這就是你如何得到以前的viewController,查看解釋說明:

// 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:.plain, target:self.revealViewController(),action: #selector(SWRevealViewController.revealToggle(_ :))) navigationItem.leftBarButtonItem = menuButton 所以沒有導航控制器使用這就是爲什麼計數返回零,當我試着你的代碼dosn't打印任何東西 –

+0

這是一個很好的答案,但沒有幫我在這種情況下,我寫了我的答案(幫助我的方式) –

1

在Second ViewController中添加第一個ViewController類型的變量。

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

現在從First ViewController執行segue到Second ViewController。

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

在prepare segue函數中,將第一個視圖控制器對象放入目標中。

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

而現在,當您需要以前的視圖控制器或者其數據,使用previousVC

+0

看到編輯帖子 我不使用準備segue我想要得到UIViewController在哪裏菜單打開 –

+0

你知道如何寫這一行在目標c var previousVC = FirstViewController() –

1

如果訪問您的ViewControllers被嵌入到一個NavigationController中,你可以在你的第二個VC中使用標準popViewController函數:

_ = navigationController?.popViewController(animated: true) 
相關問題