在设备旋转时保持自动布局约束处于活动状态 [英] Keep autolayout constraints active status on device rotation

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

问题描述

我注意到,当我以编程方式更新我的自动布局约束时,所有更改都会在我旋转屏幕时还原.

I noticed that when I update my autolayout constraints programmatically, all changes are reverted when I rotate the screen.

重现问题:

  • 带有 UIView 和 2 个约束的基本 Storyboard 界面:

  • Basic Storyboard interface with UIView and 2 constraints:

  1. 宽度等于 superview.width(乘数 1)激活
  2. 宽度等于 superview.width(乘数 1/2)已禁用

  • 使用 IBOutlet 创建和链接这两个约束

  • Create and link these 2 constraints with IBOutlet

    对我来说似乎是一个错误.

    Seems like a bug to me.

    你怎么看?

    截图:

    故事板:

    约束 #1:

    约束 #2:

    推荐答案

    Size Classes

    Installed 是指 Size Classes 安装,而不是 active/inactive.

    Size Classes

    Installed refers to Size Classes installation, not to active/inactive.

    您必须以编程方式创建另一个约束,并激活/停用那个一个.这是因为您无法更改约束的乘数(我可以更改乘数属性NSLayoutConstraint?),你也不能修改大小类(activateConstraints: 和 deactivateConstraints: 在 IB 中创建的约束旋转后不持久).

    You must create another constraint programmatically, and activate/deactivate that one. This is because you cannot change the multiplier of a constraint (Can i change multiplier property for NSLayoutConstraint?), nor can you tinker with Size Classes (activateConstraints: and deactivateConstraints: not persisting after rotation for constraints created in IB).

    有几种方法可以做到这一点.在下面的示例中,我创建了一个 x1 约束的副本,其中包含一个乘数或 1/2.然后我在两者之间切换:

    There are a few ways to do so. In the example below, I create a copy of your x1 constraint, with a multiplier or 1/2. I then toggle between the two:

    @IBOutlet var fullWidthConstraint: NSLayoutConstraint!
    var halfWidthConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        halfWidthConstraint = NSLayoutConstraint(item: fullWidthConstraint.firstItem,
            attribute: fullWidthConstraint.firstAttribute,
            relatedBy: fullWidthConstraint.relation,
            toItem: fullWidthConstraint.secondItem,
            attribute: fullWidthConstraint.secondAttribute,
            multiplier: 0.5,
            constant: fullWidthConstraint.constant)
        halfWidthConstraint.priority = fullWidthConstraint.priority
    }
    
    @IBAction func changeConstraintAction(sender: UISwitch) {
        if sender.on {
            NSLayoutConstraint.deactivateConstraints([fullWidthConstraint])
            NSLayoutConstraint.activateConstraints([halfWidthConstraint])
        } else {
            NSLayoutConstraint.deactivateConstraints([halfWidthConstraint])
            NSLayoutConstraint.activateConstraints([fullWidthConstraint])
        }
    }
    

    <小时>

    iOS 9+Xcode 7+ 上测试.

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

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