Home > database >  Best way to change colors throughout app in SwiftUI
Best way to change colors throughout app in SwiftUI

Time:06-15

Novice dev here. I'm currently working on an app that allows the color scheme to be toggled between dark and light mode. I'm trying to set custom colors that will change across the app. I've got a working implementation but I'm not sure its the best way of doing it. I've got a class set up as an ObservableObject. The class contains a struct with the list of colors and has properties that decide which colors from that list to apply depending on the status.

class CustomColorScheme: ObservableObject {
    
    @AppStorage("darkModeEnabled", store: .standard) var darkModeEnabled: Bool = false

    var backgroundColor: Color {
        darkModeEnabled ? colorList.darkGrey : colorList.offWhite
    }

    struct colorList {
        static let offWhite = Color(red: 0.941, green: 0.941, blue: 0.941)
        static let darkGrey = Color(red: 0.145, green: 0.145, blue: 0.145)
    }
}

Which works ok. But I'm losing it when I'm trying to animate the change, instead of a hard switch between the two. Currently I'm doing this.

struct MyView: View {
    @StateObject var customColors: CustomColorScheme
    var body: some View {
       Rectangle()
          .foregroundColor(customColors.backgroundColor).animation(.default)
    }
}

The animation modifier is deprecated and I apparently should be using withAnimation but I've got no idea how to apply that in this instance. Is this really the best way?

CodePudding user response:

Does your code even compile? StateObject should have a default value. Something like this:

@StateObject var customColors = CustomColorScheme()

To be able to observe an animation, the first thing that needs to happen is view redraw. Change in darkModeEnabled value can force the redraw.

To view the animation, you'd have something like:

.foregroundColor(customColors.darkModeEnabled)
.animation(Animation.easeIn(duration: 2), value: customColors.darkModeEnabled)
  • Related