Completion handler for UINavigationController “pushViewController:animated”?

前端 未结 9 1057
礼貌的吻别
礼貌的吻别 2020-11-30 18:08

I\'m about creating an app using a UINavigationController to present the next view controllers. With iOS5 there´s a new method to presenting UIViewControl

9条回答
  •  温柔的废话
    2020-11-30 18:13

    See par's answer for another and more up to date solution

    UINavigationController animations are run with CoreAnimation, so it would make sense to encapsulate the code within CATransaction and thus set a completion block.

    Swift:

    For swift I suggest creating an extension as such

    extension UINavigationController {
    
      public func pushViewController(viewController: UIViewController,
                                     animated: Bool,
                                     completion: @escaping (() -> Void)?) {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        pushViewController(viewController, animated: animated)
        CATransaction.commit()
      }
    
    }
    

    Usage:

    navigationController?.pushViewController(vc, animated: true) {
      // Animation done
    }
    

    Objective-C

    Header:

    #import 
    
    @interface UINavigationController (CompletionHandler)
    
    - (void)completionhandler_pushViewController:(UIViewController *)viewController
                                        animated:(BOOL)animated
                                      completion:(void (^)(void))completion;
    
    @end
    

    Implementation:

    #import "UINavigationController+CompletionHandler.h"
    #import 
    
    @implementation UINavigationController (CompletionHandler)
    
    - (void)completionhandler_pushViewController:(UIViewController *)viewController 
                                        animated:(BOOL)animated 
                                      completion:(void (^)(void))completion 
    {
        [CATransaction begin];
        [CATransaction setCompletionBlock:completion];
        [self pushViewController:viewController animated:animated];
        [CATransaction commit];
    }
    
    @end
    

提交回复
热议问题