2016-04-24 26 views
1

無論何時我在任何當前視圖中點擊左上角的「返回」按鈕,我都想回到根視圖。使用swift單擊後退按鈕時,如何從任何當前視圖返回到根視圖?

我發現popToRootViewControllerAnimated可能會有所幫助,但我不知道如何使用它,在視圖類中添加那個地方。

也許我可以使用下面的功能?

func popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? 

但是,如果我點擊後退按鈕,我該如何使用它?

+0

你可以檢查「unwind segue」,我想這正是你要找的 –

回答

4

如在正式文件"Pushing and popping stack items"

func popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? 

彈出堆棧除了根視圖 控制器上的所有視圖控制器和更新顯示說明。

你可以用它簡單地用:

@IBAction func backToRootButton(sender: UIButton) { 
     navigationController?.popToRootViewControllerAnimated(true) 
} 

此圖片可以說明,當你需要去RootViewController的: enter image description here

有了這個代碼下面你可以定製你的navigationController 後退按鈕

override func viewDidLoad { 
      super.viewDidLoad() 
      self.navigationItem.hidesBackButton = true 
      let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:") 
      self.navigationItem.leftBarButtonItem = newBackButton; 
     } 

     func back(sender: UIBarButtonItem) { 
      // Perform your custom actions 
      // ... 
      // Go back to the previous ViewController 
      //self.navigationController?.popViewControllerAnimated(true) 
      // ..or go back to the rootViewController    
    self.navigationController?.popToRootViewControllerAnimated(true) 
     } 

你決定是否需要簡單地彈出到先前的viewController或直接去根,取決於你的堆棧有多深,或者你在這一刻是誰topViewController ..

+0

,但是當我點擊通過添加導航控制器創建的左上角後退按鈕時,我該如何調用「backToRootButton」功能? – zonyang

+0

我已經用一些代碼更新了我的答案 –

相關問題