SwiftUI UITextView 协调器不起作用 [英] SwiftUI UITextView Coordinator not working
本文介绍了SwiftUI UITextView 协调器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 UIViewRepresentable
中包装了一个 UITextView
并包含一个 Coordinator
作为 UITextViewDelegate
,但事件是不叫.我做错了什么?
解决方案
必须在 makeUIView
中添加 textView.delegate = context.coordinator
来注册要接收的协调器从 UITextView
更新.
I have wrapped a UITextView
in a UIViewRepresentable
and included a Coordinator
as UITextViewDelegate
, but the events are not called. What am I doing wrong?
struct TextView : UIViewRepresentable {
typealias UIViewType = UITextView
var placeholder : String
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<TextView>) -> UITextView {
let textView = UITextView()
let placeholderLabel = UILabel()
textView.font = UIFont(name: "Helvetica", size: 16)
placeholderLabel.restorationIdentifier = "Placeholder"
placeholderLabel.text = self.placeholder
placeholderLabel.font = UIFont.italicSystemFont(ofSize: (textView.font?.pointSize)!)
placeholderLabel.sizeToFit()
textView.addSubview(placeholderLabel)
placeholderLabel.frame.origin = CGPoint(x: 25, y: (textView.font?.pointSize)! / 2 + 12)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.isHidden = !textView.text.isEmpty
return textView
}
func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<TextView>) {
uiView.text = self.text
}
class Coordinator : NSObject, UITextViewDelegate {
var parent: TextView
init(_ uiTextView: TextView) {
self.parent = uiTextView
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print("Not working")
return true
}
func textViewDidChange(_ textView: UITextView) {
print("Not working")
}
}
}
解决方案
You have to add textView.delegate = context.coordinator
to makeUIView
to register the coordinator to receive updates from UITextView
.
这篇关于SwiftUI UITextView 协调器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文