How can I pop specific View Controller in Swift

前端 未结 16 2979
一生所求
一生所求 2020-12-08 02:21

I used the Objective-C code below to pop a specific ViewController.

for (UIViewController *controller in self.navigationController.         


        
16条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 02:36

    I prefer a "real generic" and more functional approach.

    So I came up with following UINavigationController extension functions. You can also use the first function, for anything else, where you just need to access a specific VC in the navigation stack.


    Extensions

    extension UINavigationController {
        func getViewController(of type: T.Type) -> UIViewController? {
            return self.viewControllers.first(where: { $0 is T })
        }
    
        func popToViewController(of type: T.Type, animated: Bool) {
            guard let viewController = self.getViewController(of: type) else { return }
            self.popToViewController(viewController, animated: animated)
        }
    }
    

    Usage

    self.navigationController?.popToViewController(of: YourViewController.self, animated: true)
    



    This should work at least in Swift 4 and 5.

提交回复
热议问题