swiftui - SwiftUI 显示/关闭键盘
问题描述
下面的这段代码完美地显示和隐藏了 TextField 键盘,除了在运行代码时一直向我显示这个警告消息,有没有人可以帮助避免这个警告?
import UIKit
import SwiftUI
struct FirstResponderTextFiels: UIViewRepresentable {
@Binding var text: String
let placeholder: String
@Binding var showKeyboard: Bool
// Create the coordinator
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
@Binding var showKeyboard: Bool
var becameFirstResponder = false
init(text: Binding<String>, showKeyboard: Binding<Bool>) {
self._text = text
self._showKeyboard = showKeyboard
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text, showKeyboard: $showKeyboard)
}
// Create the textfield
func makeUIView(context: Context) -> some UIView {
let textField = UITextField()
textField.delegate = context.coordinator
textField.placeholder = placeholder
return textField
}
func updateUIView(_ uiView: UIViewType, context: Context) {
if context.coordinator.showKeyboard {
uiView.becomeFirstResponder()
context.coordinator.showKeyboard = false
}
}
}
警告信息
解决方案
在查看代码后,我发现如果我删除这部分代码它没有任何效果,它工作正常
func updateUIView(_ uiView: UIViewType, context: Context) {
if context.coordinator.showKeyboard {
uiView.becomeFirstResponder()
context.coordinator.showKeyboard = false // <--- Remove it
}
}