在拆分视图旋转时手动设置 preferredDisplayMode 时主视图控制器内容消失

Primary view controller content disappearing when manually setting preferredDisplayMode on split view rotation

我在 iOS 中有一个自定义的 UISplitViewController 子类 8. 在横向时,我希望主要和次要 VC 的默认行为都可见 (preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible),但是当我旋转到纵向时,我希望主要 VC 显示在默认弹出窗口 (preferredDisplayMode = UISplitViewControllerDisplayModePrimaryOverlay) 中。

通过在子类上实现 -viewWillTransitionToSize: 我可以使它正常工作,但是旋转几次后主要的 VC 消失并且不会重新出现,直到我点击拆分视图的栏按钮项.

前几轮旋转动画完成块中的日志显示首选显示模式与实际显示模式相同,但经过几轮旋转后,实际显示模式卡在UISplitViewControllerDisplayModePrimaryOverlay中横向,即使首选显示模式是 UISplitViewControllerDisplayModeAllVisible.

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (self.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        BOOL isPortrait = size.height > size.width;

        if (isPortrait) {
            self.preferredDisplayMode = UISplitViewControllerDisplayModePrimaryOverlay;
        }
        else {
            self.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
        }

        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            self.dividerView.hidden = isPortrait;
        } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            NSLog(@"Preferred display mode: %ld | Actual display mode: %ld", self.preferredDisplayMode, self.displayMode);
        }];
    }
}

感谢 https://devforums.apple.com/message/1024928#1024928 我明白了。

在动画协调器的完成块中,将 preferredDisplayMode 设置为 UISplitViewControllerDisplayModeAutomatic 使其工作。

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (self.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        BOOL isPortrait = size.height > size.width;

        if (isPortrait) {
            self.preferredDisplayMode = UISplitViewControllerDisplayModePrimaryOverlay;
        }

        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            if (isPortrait) {
                self.preferredDisplayMode = UISplitViewControllerDisplayModePrimaryOverlay;
            }
            self.dividerView.hidden = isPortrait;
        } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            // ADD THIS TO THE COMPLETION BLOCK
            self.preferredDisplayMode = UISplitViewControllerDisplayModeAutomatic;

            NSLog(@"Preferred display mode: %ld | Actual display mode: %ld", self.preferredDisplayMode, self.displayMode);
        }];
    }
}