为什么在`viewWillTransitionToSize`中检索SafeAreaInsets的逻辑有点错误?

问题描述

我正在探索当从纵向旋转到横向时,是否可以在 viewWillTransitionToSize 中准确地知道景观“安全区域插图”。

我看过这个 SO 答案,它的代码一个代码https://stackoverflow.com/a/46581783/2567725

在我的 iPhone XR 上,纵向插图为 {48,34,0},横向插图为 {0,48,21,48}。 像这样:

enter image description here

旋转设备时 - 从纵向到横向 - 我在 animatealongsideTransition 中记录了“未来”插图,它们是正确的。 问题是,为什么这些正确的值是从 FromViewControllerKey 中检索的,而不是从 ToViewControllerKey 中检索的:

- (void)logSafeAreaInsets:(id<UIViewControllerTransitionCoordinatorContext>)context
{
    UIInputViewController* vcFrom = [context viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIEdgeInsets iiFrom = vcFrom.view.safeAreaInsets;
    UIInputViewController* vcTo = [context viewControllerForKey:UITransitionContextToViewControllerKey];
    UIEdgeInsets iiTo = vcTo.view.safeAreaInsets;
    NSLog(@"TAdam from=%@ to=%@",NsstringFromUIEdgeInsets(iiFrom),NsstringFromUIEdgeInsets(iiTo));
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animatealongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        
        [self logSafeAreaInsets:context];
        
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            
    }];
}

对于 ToViewControllerKey,它们是 {0,0} ! 日志如下所示:

TAdam from={0,48} to={0,0}

据我所知,ToViewControllerKey 是横向 VC(旋转后),而 FromViewControllerKey 是纵向 VC(旋转前)。

所以我可以得到我想要的UIViewControllerTransitionCoordinatorContext,但它的逻辑似乎是错误的:

  1. 为什么真正的景观插图是从 FromVC 中检索的,而不是从 ToVC 中检索的?
  2. 为什么 ToVC 的插图在 animatealongsideTransition 中为零?

解决方法

嗯,逻辑不是“有点错误”,只是没有记录。 事实证明,vcTo 在我的代码中是 nil。所以插图是 zerovcTo 为零,因为屏幕旋转动画只用一个 VC 完成,不像例如推送/呈现新 VC 时的过渡动画。

我猜 vcFrom 已经在 Landscape 中插入了 animateAlongsideTransition,因为 model layer treepresentation layer tree 之间的差异 - 虽然我还不知道如何检验这个假设。