【问题标题】:How to Dismiss all push and presented screens with single button action如何通过单个按钮操作关闭所有推送和呈现的屏幕
【发布时间】:2019-09-13 06:29:55
【问题描述】:

我有 3 个视图控制器 HomePageControllerChangePasswordViewControllerPasswordChangedDoneController

在主页更改密码按钮操作中,我将屏幕推入ChangePasswordViewController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChangePasswordViewController")as! ChangePasswordViewController
self.navigationController?.pushViewController(vc, animated: true)

现在我将屏幕ChangePasswordViewController 呈现给PasswordChangedDoneController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "PasswordChangedController")as! PasswordChangedDoneController
self.navigationController?.present(vc, animated: true, completion: nil)

现在我想使用 PasswordChangedDoneController 中的 Gotit 按钮操作转到 HomePageController。 在这里,我想通过单个操作同时删除 push 和 present。

【问题讨论】:

    标签: ios swift dismiss presentviewcontroller


    【解决方案1】:

    您可以使用此函数弹出给定控制器的类类型

    extension UIViewController {
    
        /// like UIViewController.popToRoot
        public func popToRoot() {
            guard let navigationController = navigationController else { return  dismiss(animated: true) }
            navigationController.popToRootViewController(animated: true)
        }
    
        /// like UIViewController.popTo(:)
        public func popTo(_ vc: UIViewController.Type, _ orPopToRoot: Bool = true) {
            guard let navigationController = navigationController else { return popToRoot() }
            let list = navigationController.viewControllers.reversed().filter { return $0.isKind(of: vc) }
            guard let c = list.first else {
                if orPopToRoot { self.popToRoot() }
                else { self.popSelf(animated: true) }
                return
            }
            navigationController.popToViewController(c, animated: true)
        }
    
        /// like UIViewController.popViewController
        ///
        /// - Note: if can't found navigationController. will 'dismiss(animated:completion:)'
        public func popSelf(animated: Bool) {
            guard let navigationController = navigationController else { return  dismissSelf(animated: animated) }
            navigationController.popViewController(animated: animated)
        }
    
        /// like UIViewController.dismiss
        public func dismissSelf(animated: Bool, completion: (() -> Void)? = nil) {
            dismiss(animated: animated, completion: completion)
        }
    }
    

    :)

    【讨论】:

    • 'base' 是我的命名空间,你可以忽略它。 'popToRoot()' 是导航控制器的 'popToRootContoller'
    • 我无法在呈现的屏幕按钮操作中获取此方法。
    • 你可以为 UIViewController 添加一个扩展,并在按钮的选择器方法中调用该方法。
    • 我收到这些错误“UIViewController”类型的值没有成员“popToRoot”。 'UIViewController' 类型的值没有成员 'popSelf'
    猜你喜欢
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多