You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

切换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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:03:08