Swift UITextView 事件监听器

标签 swift

我的问题是,如果用户在 UITextView 中输入了一个字符,我该如何设置一个事件监听器来监听?

我知道我可以使用 textview.hasText() 来检查它是否有文本,但我需要监听输入的字符,即使 UITextView 中已经有文本也是如此。

最佳答案

看看UITextViewDelegate .

例如,如果你有

@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/

相关文章:

ios - cellForItemAt 未在 collectionView 中调用

ios - 使用私钥和 TouchID 或 FaceID swift 对消息进行签名

ios - 在导航栏顶部查看

ios - 快速将具有分层 TableView 的导航 Controller 放入 View Controller 中

ios - GameCenter 显示 "No Challenges Screen"

ios - 覆盖 touchesBegan : Error - method does not override any method from superclass

swift - 所需初始化的访问控制

ios - 如何在 Swift 中实现简单的 MVC 设计模式?

ios - 是否可以在自定义 View 中创建 @IBOutlet?

ios - firebase 和 swift - 此类不符合 key 的键值编码 -----