How can I check whether dark mode is enabled in iOS/iPadOS?

前端 未结 16 1523
囚心锁ツ
囚心锁ツ 2020-12-08 09:41

Starting from iOS/iPadOS 13, a dark user interface style is available, similar to the dark mode introduced in macOS Mojave. How can I check whether the user has enabled the

16条回答
  •  余生分开走
    2020-12-08 10:07

    The best point to detect changes is traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) function of UIView/UIViewController.

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
    
        let userInterfaceStyle = traitCollection.userInterfaceStyle // Either .unspecified, .light, or .dark
        // Update your user interface based on the appearance
    }
    

    Detecting appearance changes is trivial by overriding traitCollectionDidChange on view controllers. Then, just access the view controller’s traitCollection.userInterfaceStyle.

    However, it is important to remember that traitCollectionDidChange may be called for other trait changes, such as the device rotating. You can check if the current appearance is different using this new method:

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
    
        let hasUserInterfaceStyleChanged = previousTraitCollection.hasDifferentColorAppearance(comparedTo: traitCollection) // Bool
        // Update your user interface based on the appearance
    }
    

提交回复
热议问题