我正在使用SwiftUI的TextField View
。
我主要有两个问题,
1)在Swift中,我们可以像这样从情节提要中将TextField的返回键(文本输入特征)设置为Next
吗?为此,在SwiftUI中使用哪个修饰符?
2)我有两个文本字段,当我单击键盘上的返回/下一个按钮时,如何导航到下一个文本字段?
任何人都可以帮助执行此功能或其他替代方法吗?
我的问题是关于SwiftUI而不是UIKit:)
任何帮助将不胜感激!
答案 0 :(得分:6)
要解决两个问题,您需要使用 SwiftUI 中的 UIKit 。首先,您需要使用 UIViewRepresentable 自定义 TextField 。这是用于测试目的的示例代码,尽管该代码不是那么优雅。我敢打赌,将会有一个更强大的解决方案。
这是示例代码:
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
}
}
}
答案 1 :(得分:1)
截至 2021 年 6 月 15 日,它仍处于测试阶段。
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)
我想出了以下针对文本字段数组的实现。
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