Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift force dark/light mode inside an app

Tags:

ios

swift

ios13

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
        }
    } 
}
like image 643
evevF Avatar asked Nov 07 '25 16:11

evevF


2 Answers

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

like image 73
Lucky Mehndiratta Avatar answered Nov 09 '25 09:11

Lucky Mehndiratta


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
}

}

like image 20
evevF Avatar answered Nov 09 '25 09:11

evevF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!