iOS 在设备旋转时更改自动布局约束 [英] iOS change auto layout constraints when device rotates

查看:18
本文介绍了iOS 在设备旋转时更改自动布局约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在设备旋转时修改布局约束.我的 UIViewController 由 2 个 UIViews 组成,横向对齐,在纵向中,它们是垂直对齐的.

I want to modify the layout constraints when the device rotates. My UIViewController is composed of 2 UIViews, in landscape they are horizontally aligned, and in portrait they are vertically aligned.

它确实有效,在 willAnimateRotationToInterfaceOrientation 中,我删除了所需的约束并用其他约束替换它们以获得正确的布局...

It does work actually, in willAnimateRotationToInterfaceOrientation, I remove the desired constraints and replaced them with others to have the right layout...

但是有问题,在旋转期间,自动布局在调用 willAnimateRotationToInterfaceOrientation 之前开始打破约束,那么当设备重新定向发生时,我们打算在哪里替换我们的约束?

But there are problems, during rotation auto layout starts breaking constraints before willAnimateRotationToInterfaceOrientation is called, so where are we meant to replace our constraints when the device reorientation occurs ?

另一个问题是性能,经过几次旋转后,系统不再打破限制,但我的性能下降很大,尤其是在纵向模式下...

Another issue is performance, after a few rotations the system doesn't break anymore constraints, but I have a huge performance drop, especially in portrait mode...

推荐答案

willRotateToInterfaceOrientation:duration: 中,将 setNeedsUpdateConstraints 发送到任何需要修改其约束的视图.

In willRotateToInterfaceOrientation:duration:, send setNeedsUpdateConstraints to any view that needs its constraints modified.

或者,创建一个 UIView 子类.在您的子类中,注册以接收 UIApplicationWillChangeStatusBarOrientationNotification.当您收到通知时,向自己发送 setNeedsUpdateConstraints.

Alternatively, make a UIView subclass. In your subclass, register to receive UIApplicationWillChangeStatusBarOrientationNotification. When you receive the notification, send yourself setNeedsUpdateConstraints.

这会在视图上设置 needsUpdateConstraints 标志.在系统执行布局之前(通过发送 layoutSubviews 消息),它会向任何设置了 needsUpdateConstraints 标志的视图发送 updateConstraints 消息.这是您应该修改约束的地方.创建一个 UIView 子类并覆盖 updateConstraints 以更新您的约束.

This sets the needsUpdateConstraints flag on the view. Before the system performs layout (by sending layoutSubviews messages), it sends an updateConstraints message to any view that has the needsUpdateConstraints flag set. This is where you should modify your constraints. Make a UIView subclass and override updateConstraints to update your constraints.

这篇关于iOS 在设备旋转时更改自动布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆