我如何“禁用"约束而不删除它们? [英] How do I "disable" constraints without removing them?

查看:156
本文介绍了我如何“禁用"约束而不删除它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在人像模式和风景模式下工作的应用程序.当我转动设备时,一些标签和按钮没有显示,所以我希望将它们放在侧面.

I have a app which works on portrait mode and landscape mode. When I turn around my device, some of my labels and buttons are not shown, so I would like to have them on the side.

有一种消除约束的方法

[self.view removeConstraint:myConstraint];

此方法消除了约束,因此当我将设备转回纵向模式时,我必须使用真正令人沮丧的代码再次创建约束.

This method removes the constraint, so when I turn the device back to portrait mode, I have to create the constraints again with code which is really frustrating.

有什么方法可以禁用约束而不实际删除约束吗?

Is there any way to just disable constraint without actually removing them?

推荐答案

此方法消除了约束,因此当我将设备转回纵向模式时,我必须使用真正令人沮丧的代码再次创建约束.

This method removes the constraint, so when I turn the device back to portrait mode, I have to create the constraints again with code which is really frustrating.

停下来,问问自己为什么它确实令人沮丧".不应该这样!如果是这样,则说明您做错了.

Stop and ask yourself why it's "really frustrating". It shouldn't be! If it is, you're doing it wrong.

删除约束并将其替换为其他约束是标准过程,而且确实很容易.将约束移入和移出接口是您移动事物的方式,尤其是作为响应旋转而更改接口的一种方式.这只是让所有鸭子连续排成一列的问题.将一组约束放在一个数组中;将另一组约束放在另一个数组中;当需要交换时,删除一组并添加另一组!尽可能简单.

Removing constraints and replacing them with other constraints is standard procedure, and is really easy. Swapping constraints in and out of the interface is how you move things around, especially as a way of changing the interface in response to rotation. It's just a question of getting all your ducks in a row. Put one set of constraints in one array; put another set of constraints in another array; and when it's time to swap, remove one set and add the other! Simple as can be.

这是一些实际的代码(它是Swift,但不会对任何代码造成伤害):

Here's some actual code (it's Swift, but that won't hurt any):

func doSwap(landscape:Bool) {
    if landscape {
        NSLayoutConstraint.deactivateConstraints(self.constraintsWith)
        NSLayoutConstraint.activateConstraints(self.constraintsWithout)
    } else {
        NSLayoutConstraint.deactivateConstraints(self.constraintsWithout)
        NSLayoutConstraint.activateConstraints(self.constraintsWith)
    }
}

请注意iOS-8新增功能NSLayoutConstraint.deactivateConstraintsNSLayoutConstraint.activateConstraints的使用.这是一个真正的节省工作的方法,因为您不需要将约束附加到任何特定的视图上.它会自动为您完成.

Note the use of the new-in-iOS-8 NSLayoutConstraint.deactivateConstraints and NSLayoutConstraint.activateConstraints. This is a real work-saver because you don't need to attach the constraints to any particular view; it's done for you, automatically.

这篇关于我如何“禁用"约束而不删除它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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