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

我怕爱的太早我们不能终老 提交于 2020-04-07 05:26:09

问题


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?!

来源:https://stackoverflow.com/questions/60693733/tab-to-next-text-field-when-next-return-key-hit-on-keyboard-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!