WWDC24 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!

1      

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

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, 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!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.