iOS:为什么layoutIfNeeded调用traitCollectionDidChange? (自动版式)

时间:2015-09-24 18:29:24

标签: ios swift autolayout

我很困惑他为什么会这样?如果您在此示例中调用layoutIfNeeded,则会在引擎盖下调用traitCollectionDidChange。在致电super函数之前,我需要完成一些工作。

import UIKit

class SomeViewController: UIViewController {

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

        print(1)

//      self.view.layoutIfNeeded()

        print(2)
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    }

    override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {

        super.traitCollectionDidChange(previousTraitCollection)

        print(3)
    }
}

我认为此示例将打印1, 2, 3,但如果我调用1, 3, 2, 3,则会打印self.view.layoutIfNeeded()。任何类型的错误还是这个?

1 个答案:

答案 0 :(得分:0)

今天被这个问题咬住了,更糟糕的是,当调用traitCollectionDidChange时,hasDifferentColorAppearanceComparedToTraitCollection变为true,并且如果您碰巧在layoutIfNeeded中调用了traitCollectionDidChange,则结束了与堆栈溢出。据我测试,它仅在iOS 13上发生,iOS 14则没有。

    if ([self.traitCollection
            hasDifferentColorAppearanceComparedToTraitCollection:
                previousTraitCollection]) {
      [self updateViewsTriggingLayoutIfNeededAgain];
    }