UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.