第九块石头

rootViewController 更改动画的注意事项

| Comments

WindowrootViewController属性在 iOS5 之后都期望被设置,因为旋转等原因,controller 控制 View 比自己控制 View 更安全。

但是突然出现一个需求,需要更换主WindowrootViewController,那如何做UIView动画呢?

1
2
3
4
5
6
7
[UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                  duration:0.4
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    [[[UIApplication sharedApplication].delegate window] setRootViewController:vc];
                }
                completion:NULL];

咋看之下没啥问题,运行起来也没问题。能成功实现替换为新的vc

然后出现一个很诡异的问题——如果设备是横的,新的vc对应的View会有一个旋转的动画,导致动画混乱,甚至很奇怪的动画。

刚开始以为是vc.view加载太慢,后来没解决。Google 了一下,发现有人解决了。将上面的代码改为:

1
2
3
4
5
6
7
8
9
10
[UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                  duration:0.4
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    BOOL oldState = [UIView areAnimationsEnabled];
                    [UIView setAnimationsEnabled:NO];
                    [[[UIApplication sharedApplication].delegate window] setRootViewController:vc];
                    [UIView setAnimationsEnabled:oldState];
                }
                completion:NULL];

Comments

comments powered by Disqus