如何在设备旋转时更改自动布局约束?

问题描述 投票:4回答:2

我在相应的视图控制器中将IB中的约束设置为IBOutlet。我在IB和故事板中设置的此类约束的值是纵向方向。我需要在设备更改为横向时更改这些约束,并在再次漫游到纵向时恢复它们。

我已经阅读了几篇关于在旋转设备时更新约束的帖子,但是他们每个人都说不同的东西,我不明白过程和方法调用应该是什么......我一直在搜索关于Autolayout的Apple文档但是我没有找到任何在旋转设备时以编程方式更改约束的方法。

我对autolayout知之甚少,我真的迷失了...我很欣赏一些明确的解释,我该如何管理这个场景。

提前致谢

ios rotation autolayout orientation nslayoutconstraint
2个回答
3
投票

如果视图控制器是由窗口管理的控制器层次结构的一部分,则UIViewController接收由UIDevice通知触发的多个与方向相关的调用。

所以基本上你必须覆盖方法并在那里更新autolayout约束。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        // Landscape
        constraintName.constant = 20.0  // constraintName will be your IBoutlet Constraint
    } else {
        // Portrait
        constraintName.constant = 100.0 // constraintName will be your IBoutlet Constraint
    }
}

希望它能解决你的问题。


-2
投票

我相信,Interface Builder中的Size Classes是实现目标的最佳方式:

Link to good tutorial

Link to Apple's official docs

© www.soinside.com 2019 - 2024. All rights reserved.