【发布时间】:2019-11-17 11:21:41
【问题描述】:
我正在使用包装在 UIViewRepresentable 中的 UITextField,因此我可以在 SwiftUI 中使用它。我从几个 SO 答案中拼凑出这个。
struct RADTextField: UIViewRepresentable {
@ObservedObject var dataVM: DataVM
var placeholder: String
var isFirstResponder: Bool = false
func makeUIView(context: UIViewRepresentableContext<RADTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
textField.delegate = context.coordinator
textField.clearButtonMode = .whileEditing
textField.returnKeyType = .done
textField.placeholder = self.placeholder
textField.adjustsFontForContentSizeCategory = true
return textField
}
func makeCoordinator() -> RADTextField.Coordinator {
return Coordinator(dataVM: self.dataVM)
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<RADTextField>) {
uiView.text = dataVM.fieldOne
if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
uiView.becomeFirstResponder()
context.coordinator.didBecomeFirstResponder = true
}
}
}
协调员:
extension RADTextField {
class Coordinator: NSObject, UITextFieldDelegate {
@ObservedObject var dataVM : DataVM
var didBecomeFirstResponder = false
init(dataVM: DataVM) {
self.dataVM = dataVM
}
func textFieldDidChangeSelection(_ textField: UITextField) {
self.dataVM.fieldOne = textField.text ?? ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Update Cursor
let positionOriginal = textField.beginningOfDocument
let cursorLocation = textField.position(from: positionOriginal, offset: (range.location + string.count))
if let txt = textField.text {
textField.text = NSString(string: txt).replacingCharacters(in: range, with: string)
}
// ✳️ I think this is where the issue is ✳️
if let cursorLocation = cursorLocation {
textField.selectedTextRange = textField.textRange(from: cursorLocation, to: cursorLocation)
}
return false
}
}
}
问题是,当我尝试手动将光标放在文本中的某处并键入表情符号时,我键入的下一个字符将“拆分”表情符号。我认为某些表情符号字符实际上是两个字符,但我不知道如何处理。我用✳️标记了代码,表示我认为问题出在哪里。
【问题讨论】:
-
你有没有想过这个问题?
-
不。 SwiftUI 文本字段太乱了,我最终将数据输入屏幕更改为 UIKit。不过,我还没有尝试过 iOS 14 中的新 SwiftUI 功能。也许他们改进了其中的一些东西。