且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UINavigationController的完成处理程序" pushViewController:animated"?

更新时间:2022-12-08 22:55:47

请参阅 par的回答另一个和更新的解决方案

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

UINavigationController 动画以 CoreAnimation ,因此将代码封装在 CATransaction 中是有意义的,从而设置完成块。

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

Swift

对于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()
  }

}

用法:

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

Objective-C

标题:

#import <UIKit/UIKit.h>

@interface UINavigationController (CompletionHandler)

- (void)completionhandler_pushViewController:(UIViewController *)viewController
                                    animated:(BOOL)animated
                                  completion:(void (^)(void))completion;

@end

实施:

#import "UINavigationController+CompletionHandler.h"
#import <QuartzCore/QuartzCore.h>

@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