I'm trying to make a custom TextField which eventually show errors when loosing focus in a normal form, foreach TextField, I write:
TextField(label, text: $text)
.focused($checkoutInFocus, equals: <some Value>)
Text(textError)
.foregroundColor(.red)
.frame(height: textError == "" ? 0 : 20)
(I want to precise it's not all: I have many modifiers for the TextField and it becomes very difficult to read when there are many TextFields)
So I thought it would be a good idea to make a special view for each Textfield:
struct TextFieldWithError: View {
var label: String
@Binding var text: String
@Binding var textError: String
@FocusState.Binding var isFocused: Bool
init(label: String, text: Binding<String>, textError: Binding<String>, isFocused: FocusState<Bool>.Binding) {
self.label = label
self._text = text
self._textError = textError
self._isFocused = isFocused
}
var body: some View {
TextField(label, text: $text)
.modifier(TextFieldStyle())
.focused($isFocused)
Text(textError)
.foregroundColor(.red)
.frame(height: textError == "" ? 0 : 20)
}
}
My problem is that I don't find the way to act on the focusState.
In the mainView I write:
TextFieldWithError(label: "Email", text: $email, textError: $emailError, isFocused: checkoutInFocus == .<some Value>)
in place of the modifier
.focused($checkoutInFocus, equals: .email)
but the syntax is obviously not good: I get the error:
Cannot convert value of type 'Bool' to expected argument type 'FocusState<Bool>.Binding'
Do you think there is a way?