iOS change auto layout constraints when device rotates(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 在设备旋转时更改自动布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:iOS 在设备旋转时更改自动布局约束
基础教程推荐
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
