我正在重写traitCollectionDidChange(_)
来更新我的紧凑和常规约束。当我通过旋转在设备上测试这一点时,约束得到正确更新。然而,当我尝试在模拟器中测试相同的代码时,什么也没有发生。我插入了打印语句,我可以看到在模拟器旋转时没有任何反应。这是一个错误,还是我需要为模拟器做一些特殊的事情?
提前致谢。顺便说一句,我正在使用 Xcode 8.2.1。
这是我的代码:
private var compactConstraints: [NSLayoutConstraint] = []
private var regularConstraints: [NSLayoutConstraint] = []
private var sharedConstraints: [NSLayoutConstraint] = []
...
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if (!sharedConstraints[0].isActive) {
// activating shared constraints
NSLayoutConstraint.activate(sharedConstraints)
}
if (self.traitCollection.containsTraits(in: UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClass.compact))) {
print("going to activate: compact")
if regularConstraints.count > 0 && regularConstraints[0].isActive {
NSLayoutConstraint.deactivate(regularConstraints)
}
// activating compact constraints
NSLayoutConstraint.activate(compactConstraints)
} else {
print("going to activate: regular")
if compactConstraints.count > 0 && compactConstraints[0].isActive {
NSLayoutConstraint.deactivate(compactConstraints)
}
// activating regular constraints
NSLayoutConstraint.activate(regularConstraints)
}
}
控制台输出如下:
[launch app]
`going to activate: compact`
[rotate the simulator with ⌘ arrow key]
`going to activate: compact`
基于 hoshy
问题的小更新:
我正在 iPhone 设备上使用模拟器。特别是 iPhone SE。
最佳答案
对于两个方向,
horizontalSizeClass
都是Compact
。对于 iPhone SE,verticalSizeClass
对于 portrait
是 regular
,对于 landscape
是 Compact
。您可以更改此行
if (traitCollection.containsTraits(in: UITraitCollection(verticalSizeClass: .compact))) {
或者简单地
if traitCollection.verticalSizeClass == .compact {
如果您正在寻找与尺寸更改动画一起运行的动画,您还可以使用viewWillTransitionToSize:withTransitionCoordinator:
。
Building an Adaptive Interface来自苹果开发者
If your Auto Layout constraints are insufficient to achieve the look you want, you can use the
viewWillTransitionToSize:withTransitionCoordinator:
method to make changes to your layout. You can also use that method to create additional animations to run alongside the size-change animations. For example, during an interface rotation, you might use the transition coordinator’s targetTransform property to to create a counter-rotation matrix for parts of your interface.
关于swift3 - Xcode 模拟器不调用 TraitCollectionDidChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41771478/