切换Key Window时RootViewController未触发视图生命周期方法的问题及处理
iOS切换Key Window时RootViewController生命周期回调缺失问题解决
最近做iOS开发时碰到个棘手的问题:切换Key Window的时候,原来的RootViewController收不到viewWillDisappear:、viewDidDisappear:这类生命周期回调,导致一些依赖这些回调的逻辑没法正常执行。
当时的实现代码是这样的:
SplashViewController *screenLockViewController = [[SplashViewController alloc] initWithNibName:@"SplashViewController" bundle:nil]; [self.splashWindow.rootViewController presentViewController:splashViewController animated:NO completion:nil]; [self.splashWindow makeKeyWindow]; __weak typeof(self) welf = self; [UIView transitionWithView:self.window duration:0.25 options:UIViewAnimationOptionTransitionNone animations:^{ welf.window.alpha = 0.0f; } completion:^(BOOL finished) { [welf.window setHidden:YES]; }];
后来找到了解决方案:通过手动调用UIViewController的beginAppearanceTransition:animated:和endAppearanceTransition:方法,就能手动触发对应的生命周期回调。修改后的代码如下:
SplashViewController *screenLockViewController = [[SplashViewController alloc] initWithNibName:@"SplashViewController" bundle:nil]; [self.splashWindow.rootViewController presentViewController:splashViewController animated:NO completion:nil]; [self.window.rootViewController beginAppearanceTransition:NO animated:shouldAnimate]; // 触发viewWillDisappear [self.splashWindow makeKeyWindow]; __weak typeof(self) welf = self; [UIView transitionWithView:self.window duration:0.25 options:UIViewAnimationOptionTransitionNone animations:^{ welf.window.alpha = 0.0f; [welf.window.rootViewController endAppearanceTransition]; // 触发viewDidDisappear } completion:^(BOOL finished) { [welf.window setHidden:YES]; }];
内容的提问来源于stack exchange,提问作者Octav
相关产品推荐
相关产品推荐

