此代码有效并触发:
class ViewControllerDisplay: UIViewController, UITextViewDelegate {
//.....
let textView = MyUITextView(frame: CGRect(x:10, y:20, width:270, height:65))
textView.params["dataname"] = _dataname
textView.delegate = self
view.addSubview(textView)
func textViewDidChange(_ textView: UITextView) {
print("YAAAA" + textView.text);
}
然而这不会触发
func textViewDidChange(_ textView: MyUITextView) {
print("YAAAA" + textView.text);
}
这是MyUITextView
代码
import UIKit
class MyUITextView: UITextView{
var params: Dictionary<String, Any>
required init?(coder aDecoder: NSCoder) {
self.params = [:]
super.init(coder: aDecoder)
}
init(frame: CGRect) {
self.params = [:]
super.init(frame: frame, textContainer: nil)
}
}
那么如何扩展委托以在代理中包含MyUITextView
&#39; onChange&#39;
答案 0 :(得分:0)
好吧我通过施展来弄明白了
func textViewDidChange(_ textView: UITextView) {
if let sender = textView as? MyUITextView {
let dataname = sender.params["dataname"] as? String ?? ""
print("MyUITextView: dataname" + dataname + " = " + sender.text!)
}
}
答案 1 :(得分:0)
方法textViewDidChange( textView:MyUITextView)未被调用,因为在协议UITextViewDelegate中指定了该方法,如func textViewDidChange( textView:UITextView)
如果需要从自定义类MyUITextView专门调用,则需要为此类编写协议,如:
protocol MyUITextViewDelegate {
func myTextViewDidChange(_ textView: MyUITextView)
}
添加MyUITextViewDelegate类型的字段?在MyUITextView类中:
var myDelegate: MyUITextViewDelegate?
例如在ViewControllerDisplay类的viewDidLoad类中初始化它:
override func viewDidLoad() {
super.viewDidLoad()
...
textView.myDelegate = self
...
}
类MyUITextView需要订阅UITextViewDelegate协议并实现textViewDidChange(_ textView:UITextView)方法,如果它存在,我们的协议将从myDelegate调用:
class MyUITextView: UITextView, UITextViewDelegate {
...
func someInitMethod() {
delegate = self
}
...
func textViewDidChange(_ textView: UITextView) {
myDelegate?.myTextViewDidChange(self)
}
}
最后,通过在协议MyUITextViewDelegate上签署ViewControllerDisplay类并实现必要的方法:
class ViewControllerDisplay: UIViewController, MyUITextViewDelegate {
...
func textViewDidChange(_ textView: MyUITextView) {
print("YAAAA" + textView.text);
}
}