【问题标题】:Autolayout and Device Orientation自动布局和设备方向
【发布时间】:2013-12-03 08:52:12
【问题描述】:

我正在开发一个supports portrait and landscape modes 的应用程序。我正在使用auto layout to arrange my views。由于我阅读了许多帖子,并且我意识到开发人员通常使用以下方法之一。

1.第一种方法:

实现UIViewController:updateConstraints 方法并根据设备方向更新约束。

2。第二种方法:

实现UIViewController:viewWillLayoutSubviews 方法并根据设备方向更新约束。

谁能告诉我最好的使用方法是什么?我一直在寻找结合自动旋转和自动布局的最佳实践,但还没有。谢谢。

【问题讨论】:

    标签: ios iphone autolayout device-orientation autorotate


    【解决方案1】:

    我会使用这个 UIViewController 的方法:

    - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;

    在轮换时调用,然后从那里调用-setNeedsUpdateConstraints。 如果您需要进行额外的计算或管理约束添加

    - (void)updateViewConstraints
    {
        [super updateViewConstraints];
        // do calculations if needed, like set constants
    }
    

    【讨论】:

    • 我相信在 willAnimateRotationToInterfaceOrientation 方法中不需要计算约束,因为这可以通过检查当前设备方向在 updateViewConstraints 中完成。
    • 可能我的回答不清楚,我的意思是在updateViewContraints方法中进行计算。
    • 我确认计算将在 updateViewContraints 方法中完成。但是当我在 willAnimateRotationToInterfaceOrientation 方法中调用 setNeedsUpdateConstraints 方法时,我意识到 updateViewConstraints 被多次调用。
    • willAnimateRotationToInterfaceOrientation 已折旧。请改用“viewWillTransition(调整大小:CGSize,使用协调器:UIViewControllerTransitionCoordinator)”。但考虑到 updateViewConstraints 将在视图更改之前被调用。
    【解决方案2】:

    最好的方法是两者都不使用。相反,请正确配置您的约束,以便在轮换时无需进行任何编程更改。自动布局运行时会将视图保持在您已经指定的位置。

    除了更改 .constant 的值之外,更新约束是一个真正的性能损失,应该避免。

    没有必要使用viewWillLayoutSubviews。自动布局方法是updateViewConstraints(用于视图控制器)和updateConstraints(在视图中)。

    【讨论】:

    • 但有时配置约束是不够的,因为从横向切换到纵向时布局方面可能会完全改变,反之亦然。
    • 在这种情况下,您将需要@Fr4ncis 上述答案中描述的更新约束方法之一
    • 刚刚看到这个。它可能对您有用:stackoverflow.com/questions/17772922/…
    • 是的,我刚刚看到它,我认为它类似于@Fr4ncis 解决方案。
    【解决方案3】:

    我认为最好的方法是通过检查设备方向来更新-(void)updateViewConstraints 中的约束。无需在willAnimateRotationToInterfaceOrientation 中调用setNeedsUpdateConstraints,因为当设备方向发生变化时,iO 会自动调用它。谢谢大家的努力。

    【讨论】:

      【解决方案4】:

      iOS8+

      来自以下文档:

      - (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection
                withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
      

      标准视图控制器可能会使用此方法来更改 对其管理的视图的约束。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多