我的问题是,如果用户在 UITextView 中输入了一个字符,我该如何设置一个事件监听器来监听?
我知道我可以使用 textview.hasText()
来检查它是否有文本,但我需要监听输入的字符,即使 UITextView 中已经有文本也是如此。
最佳答案
例如,如果你有
@IBOutlet weak var textView: UITextView!;
在你的 View Controller 中遵守 UITextViewDelegate 协议(protocol)
class ViewController: UIViewController, UITextViewDelegate {
// stuff
}
在你的 viewDidLoad 方法中添加
textView.delegate = self;
然后根据您想要监听的内容,实现您需要的 UITextViewDelegate 中的方法。
例如,如果您想监听 TextView 何时更改,请执行:
func textViewDidEndEditing(textView: UITextView) {
// your code here.
print(textView.text);
}
编辑:要反射(reflect)评论,请实现此方法:
func textViewDidChange(textView: UITextView) {
}
来自 Apple 的文档:
Tells the delegate that the text or attributes in the specified text view were changed by the user.
关于Swift UITextView 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36878713/