FocusState in SwiftUI and iOS 15 to detect when a TextField looses focus

Viewed 397

I have a form with a number of fields and have set up the focused modifier to allow the user to move through the form fields:

struct CustomerForm: View {
    @ObservedRealmObject var customer: Customer
    // ...

    @FocusState private var focusedField: Field?
    enum Field: Hashable {
        case nameFirst
        case nameLast
        case notes
        case phone
        case email
        case addrCity
        case addrStreet1
        case addrStreet2
        case addrPostalCode
    }

    var body: some View {
        NavigationView {
            Form {
            // ...
                TextField(
                        "City",
                        text: $customer.addrCity,
                        onCommit: { focusedField = .addrPostalCode }
                    )
                        .focused($focusedField, equals: .addrCity)
                        .submitLabel(.next)

                TextField(
                        "Postal Code",
                        text: $customer.addrPostalCode,
                    )
                        .focused($focusedField, equals: .addrPostalCode)
                        .onChange(of: customer.addrPostalCode, perform: { value in
                           // ...
                        })

Currently the onChange observer is fired each time I make a change to $customer.addrPostalCode and need it to fire when the focus is lost.

I understand I can do that with a separate @FocusState wrapper:

@FocusState private var isFocused: Bool
// ...

var body: some View {
    Form {
        TextField("Name", text: $name)
            .focused($isFocused)
            .onChange(of: isFocused) { isFocused in
                // ...
            }
    }
}

but then I loose the ability to move through the fields with the Field enum.

Is it possible to use the onChange observer with my Field enum?//

0 Answers
Related