如何响应 TextView 文本的编程更改 [英] How to respond to programmatic changes of a TextView text
本文介绍了如何响应 TextView 文本的编程更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TextView 委托已设置:
The TextView delegate is set:
textView.delegate = self //self being a UITextViewDelegate
但是在以编程方式
but the delegate method doesn't get called when the text is set programmatically
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
}
如何在不响应的情况下响应文本更改?
How to respond to text changes without going reactive?
推荐答案
我刚刚在 UITextView 上尝试了 KVO,
I just tried KVO on UITextView,
self.textView1.text = "You are working, but I will change you in 5 seconds"
添加您的观察者
self.textView1.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
以编程方式触发文本更改,只是一个示例,按您想要的方式进行.
Trigger text change programmatically, just an example do it the way you want.
DispatchQueue.main.asyncAfter(deadline:.now() + 5) {
self.textView1.text = "Changed after some time"
}
覆盖 KVO 方法.
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object == self.textView1{
//do your thing here...
}
}
以下 Apple 文档仅供参考
FYI from Apple docs below
注意:虽然UIKit框架的类一般不支持 KVO,你仍然可以在你的自定义对象中实现它应用程序,包括自定义视图.
Note: Although the classes of the UIKit framework generally do not support KVO, you can still implement it in the custom objects of your application, including custom views.
这篇关于如何响应 TextView 文本的编程更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文