Completion block for popViewController

后端 未结 18 1613
离开以前
离开以前 2020-12-04 06:43

When dismissing a modal view controller using dismissViewController, there is the option to provide a completion block. Is there a similar equivalent for

18条回答
  •  不思量自难忘°
    2020-12-04 07:14

    2020 Swift 5.1 way

    This solution guarantee that completion is executed after popViewController is fully finished. You can test it by doing another operation on the NavigationController in completion: In all other solutions above the UINavigationController is still busy with popViewController operation and does not respond.

    public class NavigationController: UINavigationController, UINavigationControllerDelegate
    {
        private var completion: (() -> Void)?
    
        override init(rootViewController: UIViewController) {
            super.init(rootViewController: rootViewController)
            delegate = self
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        public override func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool)
        {
            if self.completion != nil {
                DispatchQueue.main.async(execute: {
                    self.completion?()
                    self.completion = nil
                })
            }
        }
    
        func popViewController(animated: Bool, completion: @escaping () -> Void) -> UIViewController?
        {
            self.completion = completion
            return super.popViewController(animated: animated)
        }
    }
    

提交回复
热议问题