SwiftUI-如何通过单击键盘上的返回按钮在TextField中导航?

时间:2019-09-26 17:15:51

标签: ios textfield swiftui

我正在使用SwiftUI的TextField View。 我主要有两个问题,

1)在Swift中,我们可以像这样从情节提要中将TextField的返回键(文本输入特征)设置为Next吗?为此,在SwiftUI中使用哪个修饰符?

enter image description here

2)我有两个文本字段,当我单击键盘上的返回/下一个按钮时,如何导航到下一个文本字段?

任何人都可以帮助执行此功能或其他替代方法吗?

我的问题是关于SwiftUI而不是UIKit:)

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:6)

要解决两个问题,您需要使用 SwiftUI 中的 UIKit 。首先,您需要使用 UIViewRepresentable 自定义 TextField 。这是用于测试目的的示例代码,尽管该代码不是那么优雅。我敢打赌,将会有一个更强大的解决方案。

  1. 在自定义的TextFieldType中,Keyboard返回类型具有 被设置。
  2. 通过使用对象绑定和委托方法 textFieldShouldReturn ,View可以通过更新绑定变量来使键盘聚焦。

这是示例代码:

import SwiftUI

struct KeyboardTypeView: View {
    @State var firstName = ""
    @State var lastName = ""
    @State var focused: [Bool] = [true, false]

    var body: some View {
        Form {
            Section(header: Text("Your Info")) {
                TextFieldTyped(keyboardType: .default, returnVal: .next, tag: 0, text: self.$firstName, isfocusAble: self.$focused)
                TextFieldTyped(keyboardType: .default, returnVal: .done, tag: 1, text: self.$lastName, isfocusAble: self.$focused)
                Text("Full Name :" + self.firstName + " " + self.lastName)
            }
        }
}
}



struct TextFieldTyped: UIViewRepresentable {
    let keyboardType: UIKeyboardType
    let returnVal: UIReturnKeyType
    let tag: Int
    @Binding var text: String
    @Binding var isfocusAble: [Bool]

    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField(frame: .zero)
        textField.keyboardType = self.keyboardType
        textField.returnKeyType = self.returnVal
        textField.tag = self.tag
        textField.delegate = context.coordinator
        textField.autocorrectionType = .no

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        if isfocusAble[tag] {
            uiView.becomeFirstResponder()
        } else {
            uiView.resignFirstResponder()
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: TextFieldTyped

        init(_ textField: TextFieldTyped) {
            self.parent = textField
        }

        func updatefocus(textfield: UITextField) {
            textfield.becomeFirstResponder()
        }

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

            if parent.tag == 0 {
                parent.isfocusAble = [false, true]
                parent.text = textField.text ?? ""
            } else if parent.tag == 1 {
                parent.isfocusAble = [false, false]
                parent.text = textField.text ?? ""
         }
        return true
        }

    }
}

输出: enter image description here

答案 1 :(得分:1)

截至 2021 年 6 月 15 日,它仍处于测试阶段。


iOS 15.0+

macOS 12.0+, Mac 催化剂 15.0+, tvOS 15.0+, watchOS 8.0+

<块引用>

使用 submitLabel(_:) 视图修饰符设置视图的提交标签。它采用 SubmitLabel

中指定的预定义案例 <块引用>

使用.next。它定义了一个带有 “Next” 文本的提交标签。

<块引用>

使用 onFocus(_:) 查找修改后的视图层次结构(在本例中为 TextField)何时失去焦点。当它发生时,将焦点放在下一个视图 (SecureField)

struct LoginForm: View {
    enum Field: Hashable {
        case usernameField
        case passwordField
    }
    
    @State private var username = ""
    @State private var password = ""
    @FocusState private var focusedField: Field?
    
    var body: some View {
        Form {
            TextField("Username", text: $username)
                .focused($focusedField, equals: .usernameField)
                .submitLabel(.next)
                .onFocus { isFocused in
                    if (!isFocused) {
                        focusedField = .passwordField
                    }
                }
            
            SecureField("Password", text: $password)
                .focused($focusedField, equals: .passwordField)
                .submitLabel(.done)
        }
    }
}

答案 2 :(得分:0)

您不能,SwiftUI中还没有响应者链的概念。您无法以编程方式启动对任何View的关注,因为它们实际上并不是视图本身,而只是描述应如何设置视图的结构。我猜想它最终可能会通过EnvironmentValues公开(例如行截断,自动更正等),但目前尚不存在。

答案 3 :(得分:0)

根据拉齐布·莫里克的回答, https://www.hackingwithswift.com/forums/100-days-of-swiftui/jump-focus-between-a-series-of-textfields-pin-code-style-entry-widget/765

我想出了以下针对文本字段数组的实现。

struct NextLineTextField: UIViewRepresentable {
@Binding var text: String
@Binding var selectedField: Int

var tag: Int
var keyboardType: UIKeyboardType = .asciiCapable
var returnKey: UIReturnKeyType = .next

func makeUIView(context: UIViewRepresentableContext<NextLineTextField>) -> UITextField {
    let textField = UITextField(frame: .zero)
    textField.delegate = context.coordinator
    textField.keyboardType = keyboardType
    textField.returnKeyType = returnKey
    textField.tag = tag
    return textField
}

func makeCoordinator() -> NextLineTextField.Coordinator {
    return Coordinator(text: $text)
}

func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<NextLineTextField>) {
    uiView.text = text
    context.coordinator.newSelection = { newSelection in
        DispatchQueue.main.async {
            self.selectedField = newSelection
        }
    }

    if uiView.tag == self.selectedField {
        uiView.becomeFirstResponder()
    }
}

class Coordinator: NSObject, UITextFieldDelegate {

    @Binding var text: String
    var newSelection: (Int) -> () = { _ in }

    init(text: Binding<String>) {
        _text = text
    }

    func textFieldDidChangeSelection(_ textField: UITextField) {
        DispatchQueue.main.async {
            self.text = textField.text ?? ""
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.newSelection(textField.tag)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.returnKeyType == .done {
            textField.resignFirstResponder()
        } else {
            self.newSelection(textField.tag + 1)
        }
        return true
    }
  }
}

然后将表单元素设为

class FieldElement: ObservableObject, Identifiable {
var id = UUID()
var title = ""
@Published var value = ""
var keyboard: UIKeyboardType = .asciiCapable
var returnType: UIReturnKeyType = .next

init(title: String, value: String = "", keyboard: UIKeyboardType = 
    .asciiCapable, returnType: UIReturnKeyType = .next) {
    self.title = title
    self.value = value
    self.keyboard = keyboard
    self.returnType = returnType
  }
}

并实施

struct FormView: View {

@State var formElements: [FieldElement] = [
    FieldElement(title: "Name"),
    FieldElement(title: "Address"),
    FieldElement(title: "Phone Number"),
    FieldElement(title: "Email Address", keyboard: .emailAddress, returnType: 
.done),
]

@State var selectedField = 0

var body: some View {
    VStack(alignment: .leading) {
        ForEach(Array(zip(formElements.indices, formElements)), id: \.0) { 
        index, element in
            VStack(alignment: .leading, spacing: 0) {
                Text(element.title)

                NextLineTextField(text: self.$formElements[index].value,
                    selectedField: self.$selectedField,
                    tag: index,
                    keyboardType: element.keyboard,
                    returnKey: element.returnType)
                    .frame(height: 35)
                    .frame(maxWidth: .infinity)
                    .overlay(
                        RoundedRectangle(cornerRadius: 8)
                            .stroke(Color.gray.opacity(0.5), lineWidth: 0.7)
                    )
            }.padding(.bottom, 4)
        }

        Button(action: {
            print(self.formElements.map({ $0.value }))
        }) {
            Text("Print Entered Values")
                .foregroundColor(Color.white)
                .font(.body)
                .padding()
        }.frame(height: 50)
            .background(Color.green)
            .cornerRadius(8)
            .padding(.vertical, 10)
        Spacer()
    }.padding()
  }
}

如果这很难导航,请随时查看 https://github.com/prakshapan/Utilities/blob/master/FormView.swift