Xcode 模拟器没有调用 traitCollectionDidChange

Xcode simulator not calling traitCollectionDidChange

我正在覆盖 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.

难道你的实际测试设备是iPhone而你的模拟器是iPad?不会对后者调用 traitCollectionDidChange 方法,因为两个方向都是 'regular'.

horizontalSizeClassCompact 两个方向。 verticalSizeClass 对于 portraitregular,对于 landscape 对于 iPhone SE 是 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.