swift - 在 SwiftUI 中处理 UITextView 的 UIResponder
问题描述
我正在尝试处理SwiftUI 中UIResponder
现有的子类。UITextView
我已经能够使用 Coordinator 模式来处理UITextViewDelegate
,但我遇到了UIResponder
.
在过去(使用 UIKit),我会做的NotificationCenter
是UIResponder.keyboardWillShowNotification
在UIViewController
.
在 SwiftUI 中,我不知道该放在哪里。我做了一件简单的事情,就是在 中重用 Coordinator 类makeUIView
,如下所示:
let nc = NotificationCenter.default
nc.addObserver(context.coordinator, selector: #selector(Coordinator.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: editorTextView)
但是该keyboardWillShow
方法永远不会被调用。我做错了吗?
解决方案
我建议使用 Combine Publisher,这样您就不需要弄乱选择器,但这应该可以。在这个例子中观察者/选择器模式被注释掉了,但是如果你取消注释它,观察者和发布者都应该在键盘出现时做出响应。
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
}
}
}
推荐阅读
- ruby-on-rails - Rails 从深度关联中获取计数
- microservices - 如何在 Istio 中记录请求和响应正文
- java - 提供给 orElse() 的方法不完全执行
- laravel - Laravel 工厂无法保存关系
- javascript - 尽管超时会出现 Div
- java - centos上的liquibase安装,JNI错误
- ssl - - IOException AMC java.security.cert.CertificateException:找不到与 api.mitel-amc.com 匹配的主题备用 DNS 名称
- javascript - 引导下拉多选 Onchange 不起作用
- javascript - UTF-8 编码在飞碟中不起作用
- c# - C# DateTime toString 在 Windows Server 2012 和 2016 上的行为不同