按下导航后退按钮时返回根目录

KUR*_*UKI 0 ios swift

我有方法检查何时按下导航栏中的后退按钮,并且该方法返回到根页面,但由于某种原因,它只self.navigationController?.popToRootViewController(animated: true)返回到上一页。有谁知道按下导航栏后退按钮时如何返回根目录?

override func didMove(toParentViewController parent: UIViewController?) {
    super.didMove(toParentViewController: parent)

    if parent == nil{
        self.navigationController?.popToRootViewController(animated: true)

    }

}
Run Code Online (Sandbox Code Playgroud)

这个问题中,他问如何使用什么方法来自定义后退按钮。在我的代码中,它能够检测用户何时按下后退按钮,并 self.navigationController?.popToRootViewController(animated: true) 假设将页面带回根页面,但是系统中存在某些内容阻止我的应用程序返回根页面。

Ari*_*nto 5

我认为最好的方法是在此页面创建您自己的自定义后退按钮

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

func back(sender: UIBarButtonItem) {
    // Perform your custom actions
    // ...
    // Go back to the root ViewController
    _ = navigationController?.popToRootViewController(animated: true)
}
Run Code Online (Sandbox Code Playgroud)

归功于“fr33g”的这个答案:按下 UINavigationController 的后栏按钮时执行操作