简体   繁体   中英

iOS Dark Mode trait detection

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    if #available(iOS 13.0, *) {
        if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) && traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
            //Do stuff
        }
    }
}

In the above code I am attempting to detect when the app is changing between dark mode and light mode. This is so i can swap out some images for dark mode or light mode variants (and a few other minor things)

The issue however, seems to be that this is getting called whenever the app goes into background via app switcher, and then I go back to the app, and it keeps being changed between dark mode and light mode, which does not make sense to me.

Note: you cant just let the app switcher hover and go back to the app. I need to dismiss the app switch and be on my home screen before bringing the switcher back up and going to my app.

Any idea on how to fix this scenario?

if #available(iOS 13.0, *) {
    if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection){
        if UIScreen.main.traitCollection.userInterfaceStyle == .dark { 
            //Do DARK mode stuff
        }
    }
}

We finally got this working by checking the value of UIScreen.main.traitCollection.userInterfaceStyle if it detects a differentColorAppearance and just simply acting on that mode's current interface style and this seems to work well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM