ios - 将 View Controller 推到导航 Controller 上时旋转无法正确调整插入的 View Controller 的大小

标签 ios objective-c autolayout

我看到了一个非常奇怪的问题;当用户旋转设备时将 View Controller 插入导航 Controller 会导致插入的 View Controller 不会将自身自动布局到导航 Controller 。

这是一个演示,其中按下按钮会触发pushViewController:

[ 1]

首先,您可以看到推送按预期工作(无旋转),然后推送时出现困惑(旋转),最后弹出时出现困惑(旋转)。

我特意制作了我能想到的最简单的项目来测试它,因此 Storyboard是一个 View Controller ,在导航 Controller 中带有一个按钮,整个代码是:

- (void)didTapButton:(id)sender
{
    UIViewController *viewController = [[UIViewController alloc] init];
    viewController.view.backgroundColor = [UIColor whiteColor];

    [self.navigationController pushViewController:viewController animated:YES];
}

我很难相信我在 iOS11 和 12 中遇到了迄今为​​止未被注意到的错误(10 中没有发生),但如果这是我的错,我真的不知道我可能做错了什么以某种方式。

有人以前见过这个或对我在这里缺少的东西有建议吗?

最佳答案

我的猜测是,这是某种竞争条件,与转换到不同大小时的插入有关。当转换到新尺寸完成时, updateConstraints/needsLayout 标志可能为 NO(即,它已经认为在推送完成后已经完全完成了 View 的布局,但旋转尚未完成)。我认为这是一个 Apple Bug,如果您还没有报告的话,我会报告它。

作为解决方法,您可以使用 UINavigationController 的子类并实现 viewWillTransitionToSize:withTransitionCoordinator: 然后,如果需要,抛出额外的 [self.view setNeedsLayout][ self.view setNeedsUpdateConstraints]coordinator animateAlongsideTransition:completion:

的完成 block 中
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        UIView *topView = [self.topViewController view];
        // we should only need an additional layout if the topView's size doesn't match the size
        // we're transitioning to (otherwise it should have already beend layed out properly)
        BOOL needsAdditionalLayout = topView && CGSizeEqualToSize(topView.frame.size, size) == NO;
        if (needsAdditionalLayout) {
            // either of these two should do the trick
            [self.view setNeedsUpdateConstraints];
            // [self.view setNeedsLayout];
        }
    }];
}

这似乎在尺寸转换完成后正确调整了 View 的大小。

关于ios - 将 View Controller 推到导航 Controller 上时旋转无法正确调整插入的 View Controller 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55628799/

相关文章:

ios - 如何在@selector( objective-c )中传递变量?

objective-c - 如何让插件导入 UTI 类型

objective-c - Interface Builder "locking"对象到屏幕边缘

ios - uitextfield 动画宽度约束

html - 我可以在html中更改img src吗?

ios - swift 默认自动释放吗?应用空闲时内存增长的原因是什么?

ios - 更改 UIView 的自动约束高度

ios - Swizzling 不在框架中工作

ios - 使用自动布局模仿 UITableViewCellStyleValue1 accessoryType-detailTextLabel 间距?

ios - 如何向 UITapGestureRecognizer 添加参数,以便操作函数可以访问该参数