Hi guys,
I have a problem I'm trying to solve and I can't figure out a way to do it. I have a variable in the view model that is being watched and will flash the background of a textfield red if an invalid character is entered. (This is a business requirement for a SwiftUI proof of concept at work so I cannot change this behavior.). Unfortuantely I cannot figure out how to do it.
The code below is a simplification of what I need. If you enter a "!" in the text field, the background will render red. The issue here is because it can't change back to white without a state change, the background stays red until a new character is pressed.
I'm trying to figure out a workaround to this since it doesn't seem possible to chain animations and the "repeatCount(1, autoreverses: true) doesn't do anything here. Anyone have any suggestions?
class Person: ObservableObject {
@Published var name: String = "" { willSet { processValue(value: newValue) }}
@Published var hasError: Bool = false
private func processValue(value: String) {
value.last == "!" ? (hasError = true) : (hasError = false)
}
}
struct ContentView: View {
@ObservedObject var vm = Person()
@State private var change = false
var body: some View {
VStack {
TextField("Name", text: $vm.name)
.background(vm.hasError ? Color.red : Color.white) //I'd rather just flash this red and turn it back to white
.animation(Animation.linear(duration: 0.2).repeatCount(1, autoreverses: true))
}.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}