How can I check whether dark mode is enabled in iO

2020-02-26 03:11发布

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 system-wide dark mode?

11条回答
Anthone
2楼-- · 2020-02-26 03:42

For iOS 13, you can use this property to check if current style is dark mode or not:

if #available(iOS 13.0, *) {
    if UITraitCollection.current.userInterfaceStyle == .dark {
        print("Dark mode")
    }
    else {
        print("Light mode")
    }
}
查看更多
Juvenile、少年°
3楼-- · 2020-02-26 03:42

For Swift:

if #available(iOS 12.0, *) {
  switch UIScreen.main.traitCollection.userInterfaceStyle {
    case .dark: // put your dark mode code here
    case .light: 
    case .unspecified: 
  }
}

For Objective C:

if (@available(iOS 12.0, *)) {
        switch (UIScreen.mainScreen.traitCollection.userInterfaceStyle) {
            case UIUserInterfaceStyleDark:
                // put your dark mode code here
                break;
            case UIUserInterfaceStyleLight:
            case UIUserInterfaceStyleUnspecified:
                break;
            default:
                break;
        }
}

For more information watch this WWDC2019 video

查看更多
家丑人穷心不美
4楼-- · 2020-02-26 03:43

in objective-c you'd want to do:

if( self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ){

        //is dark
}else{

    //is light

}
查看更多
放荡不羁爱自由
5楼-- · 2020-02-26 03:45

Some nice extension maybe ?

public extension UIViewController {
    @available(iOS 12.0, *)
    public var isDarkMode: Bool { traitCollection.userInterfaceStyle == .dark }
}
查看更多
看我几分像从前
6楼-- · 2020-02-26 03:47

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
}
查看更多
登录 后发表回答