我想回应键盘按键在UITextField
包装成UIViewRepresentable
.下面是包装器视图的代码:
import SwiftUI
import UIKit
struct ContentView: View {
@State var text: String = "Hello."
var body: some View {
WrappedUITextField(text: $text)
}
}
struct WrappedUITextField: UIViewRepresentable {
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
textField.text = text
textField.autocapitalizationType = .none
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
if text != context.coordinator.currentText { uiView.text = text }
}
}
class Coordinator: NSObject, UITextFieldDelegate {
var text: Binding<String>
var currentText: String
init(_ text: Binding<String>) {
self.text = text
currentText = text.wrappedValue
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text,
let textRange = Range(range, in: oldText) else {
return false
}
self.currentText = oldText.replacingCharacters(in: textRange, with: string)
print("oldText = \"\(oldText)\", new text = \"\(currentText)\"")
self.text.wrappedValue = currentText
return true
}
func textFieldDidChangeSelection(_ textField: UITextField) {
print("textFieldDidChangeSelection")
}
}
具体地说,我想要在光标位于最左/最右边缘时按下左/右箭头键时触发一些动作,例如"|ABC",其中"|"是光标位置,用户按下左箭头.
这UITextFieldDelegate
种方法在这里都不起作用,因为当光标已经位于最左/最右边缘时,按左/右箭头键既不会改变文本内容(例如,textFieldDidBeginEditing()
不会被调用),也不会改变光标位置(例如,textFieldDidChangeSelection()
不会被调用).
在这种情况下,我如何响应向左/向右箭头键?类似pressesBegan()
的方法在这里会很好,但我想不出如何将其与UIViewRepresentable
集成(例如,将override func pressesBegan(...)
与Coordinator
相加不起作用).
谢谢