我注意到,当我以编程方式更新我的自动布局约束时,所有更改都会在我旋转屏幕时还原.
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:
使用 IBOutlet 创建和链接这两个约束
Create and link these 2 constraints with IBOutlet
对我来说似乎是一个错误.
Seems like a bug to me.
你怎么看?
截图:
故事板:
约束 #1:
约束 #2:
Installed 是指 Size Classes 安装,而不是 active/inactive.
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+ 上测试.
这篇关于在设备旋转时保持自动布局约束处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!