我试图在视图出现时立即显示文本字段键盘,并在点击键盘时关闭键盘"返回";键,通过下面的代码示例解决了问题的第一部分,但这使得键盘";返回";键不起作用,任何人都可以帮助实现我的显示和消除文本字段键盘,因为我需要。
import SwiftUI
struct MyTextField: UIViewRepresentable {
typealias UIViewType = UITextField
@Binding var becomeFirstResponder: Bool
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
return textField
}
func updateUIView(_ textField: UITextField, context: Context) {
if self.becomeFirstResponder {
DispatchQueue.main.async {
textField.becomeFirstResponder()
self.becomeFirstResponder = false
}
}
}
}
struct TextFieldFirstResponder: View {
@State private var becomeFirstResponder = false
var body: some View {
MyTextField(becomeFirstResponder: self.$becomeFirstResponder)
.onAppear {
self.becomeFirstResponder = true
}
}
}
使用textFieldShouldReturn
委托方法。为此,使UIViewRepresentable的Coordinator具有代表性。
struct MyTextField: UIViewRepresentable {
typealias UIViewType = UITextField
@Binding var becomeFirstResponder: Bool
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ textField: UITextField, context: Context) {
if self.becomeFirstResponder {
DispatchQueue.main.async {
textField.becomeFirstResponder()
self.becomeFirstResponder = false
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: MyTextField
init(parent: MyTextField) {
self.parent = parent
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
}
}
}