Pop 2 view controllers in Nav Controller in Swift

后端 未结 8 1011
星月不相逢
星月不相逢 2021-01-30 12:46

I have found many ways to pop back 2 UIViewControllers in UINavigationController using Objective-C, however when I try and switch that over to Swift it

8条回答
  •  梦如初夏
    2021-01-30 13:22

    I wrote an UIViewController extension (Swift 3+ ready)

    You could use like this :

    /// pop back n viewcontroller
    func popBack(_ nb: Int) {
        if let viewControllers: [UIViewController] = self.navigationController?.viewControllers {
            guard viewControllers.count < nb else {
                self.navigationController?.popToViewController(viewControllers[viewControllers.count - nb], animated: true)
                return
            }
        }
    }
    

    Usage :

    self.popBack(3)
    

    Bonus dismiss to a specific viewcontroller

    /// pop back to specific viewcontroller
    func popBack(toControllerType: T.Type) {
        if var viewControllers: [UIViewController] = self.navigationController?.viewControllers {
            viewControllers = viewControllers.reversed()
            for currentViewController in viewControllers {
                if currentViewController .isKind(of: toControllerType) {
                    self.navigationController?.popToViewController(currentViewController, animated: true)
                    break
                }
            }
        }
    }
    

    Usage :

    self.popBack(toControllerType: MyViewController.self)
    

提交回复
热议问题