我正在尝试为SwiftUI中现有的UITextView子类处理UIResponder。我已经能够使用协调器模式来处理UITextViewDelegate,但是我在使用UIResponder时遇到了问题。
在过去(使用UIKit),我要做的是使用NotificationCenter在UIViewController的子类中添加UIResponder.keyboardWillShowNotification的观察者。
在SwiftUI中,我不知道该把它放在哪里。我做了一件简单的事情,那就是重用makeUIView中的协调器类,如下所示:
let nc = NotificationCenter.default
nc.addObserver(context.coordinator, selector: #selector(Coordinator.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: editorTextView)但是keyboardWillShow方法永远不会被调用。我做错了吗?
发布于 2020-04-14 15:38:17
我建议您使用组合发布程序,这样您就不需要使用选择器了,但这两种方式都应该可以工作。在本例中,观察者/选择器模式被注释掉了,但是如果您取消注释它,当键盘出现时,观察者和发布者都应该响应。
import Combine
import SwiftUI
import UIKit
struct MyTextView: UIViewRepresentable {
// Pass in the binding to the string from the SwiftUI view
var text: Binding<String>
init(text: Binding<String>) {
self.text = text
}
func makeUIView(context: Context) -> UITextField {
let tf = UITextField()
tf.delegate = context.coordinator
tf.text = context.coordinator.text.wrappedValue // Access the wrapped value in the binding
return tf
}
func updateUIView(_ uiView: UITextField, context: Context) {
//
}
func makeCoordinator() -> MyTextViewDelegate {
let delegate = MyTextViewDelegate(text: text)
return delegate
}
class MyTextViewDelegate: NSObject, UITextFieldDelegate {
// let nc = NotificationCenter.default
var text: Binding<String>
// You can use a Combine Publisher rather than dealing with selectors
var subscriber: AnyCancellable?
init(text: Binding<String>) {
self.text = text
super.init()
subscriber = NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
.sink() { [weak self] note in
print(self?.text.wrappedValue ?? "nil")
print("Publisher called -> " + note.description)
}
// nc.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
// @objc func keyboardWillShow(notification: Notification) {
// print("Selector called -> " + notification.description)
// }
// Value should update in SwiftUI when return key is pressed to show that the data flows
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.text.wrappedValue = textField.text ?? ""
print(textField.text!)
return true
}
}
}https://stackoverflow.com/questions/61201617
复制相似问题