WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Setting the UI to dark mode

Forums > SwiftUI

Good day!

I know how to set a bool and bind it so I can set light / dark...

preferredColorScheme(settingsDarkMode ? .dark : .light)

Of course this sets the UI dark if settingsDarkMode is true, and light if false. But i've noticed that once this is used I cannot control the light / dark by chaning the settings and put the device in light or dark mode.

What I want to do is to give the user to set the mode to dark or 'device settings' not 'light'.

Any idea how I can do that?

Thanks for any tips!

   

Add this enum

enum ColorSchemeSetting: String, CaseIterable {
    case light, dark, system
}

Then you can use

struct ContentView: View {
    //@Environment(\.colorScheme) var colorScheme Do not need this!
    @State private var chosenColorScheme = ColorSchemeSetting.system

    var selectedColorScheme: ColorScheme? {
        switch chosenColorScheme {
        case .light:
            return .light
        case .dark:
            return .dark
        case .system:
            return nil
        }
    }

    var body: some View {
        VStack {
            Picker("chose scheme", selection: $chosenColorScheme) {
                ForEach(ColorSchemeSetting.allCases, id: \.self) {
                    Text($0.rawValue.capitalized)
                }
            }
            .pickerStyle(.segmented)
        }
        .padding()
        .preferredColorScheme(selectedColorScheme)
    }
}

PS do not very well in Preview but works in the Simulator

1      

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.