ios - UITextView 委托(delegate)多次调用

标签 ios swift uitextview uitextviewdelegate

我正在使用 UITextView 并实现了委托(delegate)功能

var count = 0
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    print(text)
    count += 1
    print(count)
    return true
}

样本

enter image description here

当我从键盘选择预测文本时,shouldChangeTextInRange 委托(delegate)调用了两次。

  1. 为什么这个代表打电话两次?
  2. 为什么单独使用预测文本会发生这种情况

最佳答案

请使用此代码。它会很好地工作,希望它能完美地与您现有的逻辑一起工作。

 var count = 0
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        print(text)
        let trimmedString = text.trimmingCharacters(in: .whitespaces)
        if(trimmedString.characters.count != 0){
        count += 1
        print(count)
        }
        return true
    }

问题 1 和 2 的答案都是 当您从预测文本中选择文本时。首先,它附加单词然后它附加一个空格。这就是委托(delegate)被调用两次的原因。

关于ios - UITextView 委托(delegate)多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635581/

相关文章:

swift - UIApplication.shared.open(_ url : URL, 等) 不打开任何内容

ios - UITextField 的听写结果不同于 UITextView

ios - 从后台返回应用程序时未调用自定义委托(delegate)方法

ios - 是否可以在收到推送通知后对其进行修改?

iphone - iOS版式引用还是编程指南?

objective-c - 解析 JSON objective c

ios - TableView 在查询后未填充 (PFQuery)

ios - 无法控制单击时单元格的按钮图像变化

ios - 有没有办法知道用户移动 ScrollView 的像素数?

ios - 类似终端的应用程序 : UItextFied vs UITextView