Tab to next text field when 'next/return' key hit on keyboard in SwiftUI

Viewed 687

This is strictly for SwiftUI.

I would like to have the keyboard move to the next available text field when the user hits the 'return' key on the keyboard.

I have the following view:

var body: some View {

    VStack {

        NavigationView {

            Form {

                TextField("First name", text: $model.firstname)
                    .tag(1)

                TextField("Last name", text: $model.lastname)
                    .tag(2)

            }
            .navigationBarTitle("Add a Person", displayMode: .inline)

        }

    }

}

And the following code that should allow the tab:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    let nextTag = textField.tag + 1

    if let nextResponder = textField.superview?.viewWithTag(nextTag) {

        nextResponder.becomeFirstResponder()

    } else {

        textField.resignFirstResponder()

    }

    return true

}

I am just not sure how to implement it in SwiftUI?

How do I assign it to the delegate of the textfield?!

****UPDATE****

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    print("Current Tag: ", textField.tag) // Works correctly

    let nextTag = textField.tag + 1

    print("Next Tag: ", nextTag) // Works correctly

    let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder? // ALWAYS RETURN NIL

    ....

Not sure why the assignment of nextResponder always returns nil?!

1 Answers

iOS15+

Now it can be easily done with FocusState+.focused(,equals:) specifying named tags and updating focus state on needed action.

demo

Tested with Xcode 13.3 / iOS 15.4

Here is main part:

    @FocusState private var infocus: Field?

    enum Field {
        case first, last
    }

    // ...

    TextField("First name", text: $firstname, 
            onCommit: { infocus = .last })     // << here !!
        .focused($infocus, equals: .first)

Complete test module in project is here

Related