我有一种方法可以检查何时按下导航栏中的后退按钮,并且该方法返回到根页面,但是由于某种原因,当self.navigationController?.popToRootViewController(animated: true)
仅返回到上一页时。有谁知道按下导航栏的“后退”按钮时如何回到根目录?
override func didMove(toParentViewController parent: UIViewController?) {
super.didMove(toParentViewController: parent)
if parent == nil{
self.navigationController?.popToRootViewController(animated: true)
}
}
在this问题中,他询问如何使用哪种方法来自定义后退按钮。在我的代码中,它能够检测到用户何时按下后退按钮和self.navigationController?.popToRootViewController(animated: true)
来将页面带回到根页面,但是系统中有些东西阻止我的应用返回根页面。
答案 0 :(得分:3)
我认为最好的方法是在此页面上创建自己的自定义后退按钮
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)
}
通过“ fr33g”获得此答案的信用:Execute action when back bar button of UINavigationController is pressed
答案 1 :(得分:0)
我个人不建议您尝试实现的目标,但是无论如何,这是一种无需自定义后退按钮的解决方案。
XmlDocument xDoc = new XmlDocument();
XmlNodeList nodes = xDoc.SelectNodes("//element[@name='TranslateMe']");
UINavigationController
popViewController(animated:)
符合ViewController
且
Navigationable
返回shouldCustomNavigationControllerPopToRoot()
,致电true
super.popToRootViewController
自定义导航控制器
ViewController
符合import UIKit
class CustomNavigationController: UINavigationController {
// MARK: - Initializers
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
initialSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
// MARK: - Setups
private func initialSetup() {
// DISCLAIMER: This code does not support `interactivePopGestureRecognizer`, therefore we disable it
interactivePopGestureRecognizer?.delegate = nil
}
// MARK: - Overrides
override func popViewController(animated: Bool) -> UIViewController? {
if shouldNavigationPopToRoot {
return super.popToRootViewController(animated: animated)?.last
}
return super.popViewController(animated: animated)
}
// MARK: - Helpers
private var shouldNavigationPopToRoot: Bool {
return (topViewController as? Navigationable)?.shouldCustomNavigationControllerPopToRoot() == true
}
}
Navigationable