在UIModalPresentationOverCurrentContext上查看控制器生命周期

当我使用UIModalPresentationOverCurrentContext模式演示样式时,如何确定隐藏或显示父视图控制器的UIModalPresentationOverCurrentContext ? 在正常情况下,我可以使用viewWillAppear:viewWillDisappear: ,但它们似乎没有在此触发。

UIModalPresentationOverCurrentContext旨在用于在当前viewController上显示内容。 这意味着,如果您在parentViewController中有动画或视图更改,如果视图是透明的,您仍然可以通过childViewController查看。 因此,这也意味着对于当前上下文的视图,视图永远不会消失。 似乎合法的是viewWillAppear:,viewDidAppear:,viewWillDisappear:和viewDidDisappear都没有被调用。

但是,您可以使用UIModalPresentationStyle.Custom在当前上下文中显示完全相同的行为。 您不会收到视图外观回调,但您可以创建自己的自定义UIPresentationController来获取这些回调。

这是一个示例实现,

 class MyFirstViewController: UIViewController { .... func presentNextViewController() { let myNextViewController = MyNextViewController() myNextViewController.modalPresentationStyle = UIModalPresentationStyle.Custom myNextViewController.transitioningDelegate = self presentViewController(myNextViewController, animated: true) { _ in } } ... } extension MyFirstViewController: UIViewControllerTransitioningDelegate { func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let customPresentationController = MyCustomPresentationController(presentedViewController: presented, presentingViewController: presenting) customPresentationController.appearanceDelegate = self return customPresentationController } } extension MyFirstViewController: MyCustomApprearanceDelegate { func customPresentationTransitionWillBegin() { print("presentationWillBegin") } func customPresentationTransitionDidEnd() { print("presentationDidEnd") } func customPresentationDismissalWillBegin() { print("dismissalWillBegin") } func customPresentationDismissalDidEnd() { print("dismissalDidEnd") } } protocol MyCustomApprearanceDelegate { func customPresentationTransitionWillBegin() func customPresentationTransitionDidEnd() func customPresentationDismissalWillBegin() func customPresentationDismissalDidEnd() } class MyCustomPresentationController: UIPresentationController { var appearanceDelegate: MyCustomApprearanceDelegate! override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController) } override func presentationTransitionWillBegin() { appearanceDelegate.customPresentationTransitionWillBegin() } override func presentationTransitionDidEnd(completed: Bool) { appearanceDelegate.customPresentationTransitionDidEnd() } override func dismissalTransitionWillBegin() { appearanceDelegate.customPresentationDismissalWillBegin() } override func dismissalTransitionDidEnd(completed: Bool) { appearanceDelegate.customPresentationDismissalDidEnd() } }