我打算使用UINavigationController
创建一个应用程序来呈现下一个视图控制器。有了iOS5,有了一种表示UIViewControllers
的新方法
presentViewController:animated:completion:
现在我问自己,为什么没有针对UINavigationController
的完成处理程序?这里只有
pushViewController:animated:
可以像新的presentViewController:animated:completion:
一样创建我自己的完成处理程序吗?
发布于 2016-01-28 23:02:18
基于par's answer (它是唯一与iOS9一起工作的),但更简单,并且缺少else (这可能导致完成永远不会被调用):
extension UINavigationController {
func pushViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) {
pushViewController(viewController, animated: animated)
if animated, let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: nil) { _ in
completion()
}
} else {
completion()
}
}
func popViewController(animated: Bool, completion: @escaping () -> Void) {
popViewController(animated: animated)
if animated, let coordinator = transitionCoordinator {
coordinator.animate(alongsideTransition: nil) { _ in
completion()
}
} else {
completion()
}
}
}
发布于 2013-02-16 00:44:14
目前UINavigationController
不支持此功能。但是有一个UINavigationControllerDelegate
你可以使用。
要实现这一点,一种简单的方法是将UINavigationController
子类化并添加完成块属性:
@interface PbNavigationController : UINavigationController <UINavigationControllerDelegate>
@property (nonatomic,copy) dispatch_block_t completionBlock;
@end
@implementation PbNavigationController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.delegate = self;
}
return self;
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
NSLog(@"didShowViewController:%@", viewController);
if (self.completionBlock) {
self.completionBlock();
self.completionBlock = nil;
}
}
@end
在推送新的视图控制器之前,您必须设置完成块:
UIViewController *vc = ...;
((PbNavigationController *)self.navigationController).completionBlock = ^ {
NSLog(@"COMPLETED");
};
[self.navigationController pushViewController:vc animated:YES];
这个新的子类可以在Interface Builder中分配,也可以通过编程方式使用,如下所示:
PbNavigationController *nc = [[PbNavigationController alloc]initWithRootViewController:yourRootViewController];
发布于 2018-02-07 04:36:16
这是带有Pop的Swift 4版本。
extension UINavigationController {
public func pushViewController(viewController: UIViewController,
animated: Bool,
completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
pushViewController(viewController, animated: animated)
CATransaction.commit()
}
public func popViewController(animated: Bool,
completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
popViewController(animated: animated)
CATransaction.commit()
}
}
以防其他人需要这个。
https://stackoverflow.com/questions/9906966
复制相似问题