evevF
evevF

Reputation: 141

Swift force dark/light mode inside an app

I want user to press a button and force change the dark/light mode inside an app, code works ,but need to press twice the button to get it work, weird... can anyone take a look? thanks!

func darkOrLight() {
    let window = UIApplication.shared.keyWindow
    if #available(iOS 13.0, *) {
        if window?.overrideUserInterfaceStyle == .dark {
            window?.overrideUserInterfaceStyle = .light
        } else {
            window?.overrideUserInterfaceStyle = .dark
        }
    } 
}

Upvotes: 3

Views: 3442

Answers (3)

Rob
Rob

Reputation: 437542

This code presumes that the only two values are dark and light. But the initial UIUserInterfaceStyle value is unspecified, in which case it uses the current system setting.

Rather than having “dark” vs “light” in your app, consider giving them three choices, “dark”, “light”, and “system default”.

Upvotes: 0

Lucky Mehndiratta
Lucky Mehndiratta

Reputation: 109

func darkOrlightMode(){

    if #available(iOS 13.0, *) {

    if UIApplication.shared.keyWindow!.overrideUserInterfaceStyle == .dark {

        UIApplication.shared.keyWindow!.overrideUserInterfaceStyle = .light

    }
    else {

        UIApplication.shared.keyWindow!.overrideUserInterfaceStyle = .dark

    }
    }
}

Blockquote

Upvotes: 5

evevF
evevF

Reputation: 141

problem solved, don't use overrideUserInterFaceStyle to check current theme mode,

if #available(iOS 13.0, *) {
if UITraitCollection.current.userInterfaceStyle == .dark {
    window?.overrideUserInterfaceStyle = .light
}
else {
    window?.overrideUserInterfaceStyle = .dark
}

}

Upvotes: 0

Related Questions