为了解决你的两个问题,你需要使用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
}
}
}
macOS 12.0+, Mac Catalyst 15.0+, tvOS 15.0+,watchOS 8.0+
使用
submitLabel(_:)
视图修饰符为视图设置提交标签。它采用SubmitLabel
中指定的预定义案例。
使用
.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)
}
}
}
View
上以编程方式启动焦点,因为它们实际上并不是视图本身,只是描述如何设置视图的结构体。我猜它最终可能会通过EnvironmentValues
(例如行截断,自动更正等)公开,但目前不存在。@FocusState
和onSubmit()
来处理键盘操作。
struct TextFieldFocus: View {
enum Field {
case userName, password
}
@State var field1 = ""
@State var field2 = ""
@FocusState var focusedField: Field?
var body: some View {
VStack(spacing: 20.0) {
TextField("User name", text: $field1)
.focused($focusedField, equals: .userName)
.submitLabel(.next)
.padding()
.onSubmit {
focusedField = .password
}
SecureField("Password", text: $field2)
.focused($focusedField, equals: .password)
.submitLabel(.continue)
.padding()
.onSubmit {
focusedField = .userName
}
}
.textFieldStyle(.roundedBorder)
}
}
基于 Razib Mollick 的回答和 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()
}
}
.default
类型。或者至少对于numberPad
和decimalPad
都不起作用。如果有可能,有什么想法可以让它们工作吗? - mota