Reputation:
I am new to SwiftUI, and I want save colorScheme
to @State
wraper but it does not work, it does update the wrong value for @State
, how I should solve this problem?
My code:
import SwiftUI
struct ContentView: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
@State private var color: String = String()
var body: some View {
Text(color)
.onAppear() {
if (colorScheme == .light) {
color = "light"
}
else {
color = "dark"
}
}
.onChange(of: colorScheme) { _ in
if (colorScheme == .light) {
color = "light"
}
else {
color = "dark"
}
}
}
}
Upvotes: 0
Views: 917
Reputation: 9755
.onChange is essentially a willSet. The value is changing, but it hasn't changed yet. If you change it to:
.onChange(of: colorScheme) { newValue in
if (newValue == .light) {
color = "light"
}
else {
color = "dark"
}
}
it will work. Tested Xcode 12.2, iOS 14.2.
Upvotes: 2