在 SwiftUI 中的键盘上按下“下一个/返回”键时,选项卡到下一个文本字段

Lea*_*ode 5 keyboard textfield swiftui

这严格适用于 SwiftUI。

当用户点击键盘上的“返回”键时,我想让键盘移动到下一个可用的文本字段。

我有以下观点:

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)

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

以及应该允许选项卡的以下代码:

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

    let nextTag = textField.tag + 1

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

        nextResponder.becomeFirstResponder()

    } else {

        textField.resignFirstResponder()

    }

    return true

}
Run Code Online (Sandbox Code Playgroud)

我只是不确定如何在 SwiftUI 中实现它?

我如何将它分配给文本字段的委托?!

****更新****

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

    ....
Run Code Online (Sandbox Code Playgroud)

不知道为什么赋值nextResponder总是返回nil?!

Asp*_*eri 2

iOS15+

现在可以通过指定命名标签并更新所需操作的焦点状态来轻松FocusState完成.focused(,equals:)

演示

使用 Xcode 13.3 / iOS 15.4 进行测试

这是主要部分:

    @FocusState private var infocus: Field?

    enum Field {
        case first, last
    }

    // ...

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

Run Code Online (Sandbox Code Playgroud)

项目中完整的测试模块在这里