我正在子类化UITextView
并希望在其中处理用户输入。利用委派不是一个选项,因为应该可以将委派设置为其他内容。有人知道我该如何做到这一点吗?
有一个解决方法。您可以使用UITextViewTextDidChange
通知。
class UITextViewPlus: UITextView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NotificationCenter.default.addObserver(self, selector: #selector(textChange(_:)), name: .UITextViewTextDidChange, object: nil)
}
func textChange(_ sender: NSNotification) {
guard let textView = sender.object as? UITextViewPlus, textView == self else {
// ignoring text change of any other UITextView
return
}
// do something
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
注意:请记住UITextViewTextDidChange
发布任何UITextView
中的任何文本更改的通知。