Detect dark mode in XCUI test on real devices

Viewed 138

I'm trying to find a way to detect whether a phone is in dark mode or not in an XCUI test. So far I've got this:

    private func darkMode() -> Bool {
        if #available(iOS 13, *) {
            return UIView().traitCollection.userInterfaceStyle == .dark
        } else {
            return false
        }
    }

This works perfectly for simulators, but doesn't work for real devices. How can I achieve this for a real device?

Note: I know there is a way to set dark/light mode in an XCUI test. I don't want this, I just want to detect it.

1 Answers

Simply use traitCollectionDidChange method in your viewController like below:

//Call this method when you change UserInterface style
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    print(previousTraitCollection," preview UI mode")
}
Related