UITextView委托多次调用

我正在使用UITextView并实现了委托function

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

样品

在此处输入图像描述

当我从键盘中选择预测文本时,shouldChangeTextInRange委托正在调用两次。

  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的答案是当您从预测文本中选择文本时。 首先,它附加单词然后它附加一个空格。 这就是委托被召唤两次的原因。

只要用户键入新字符或删除现有字符,文本视图就会调用此方法。 此方法的实现是可选的。 在将文本提交到文本视图存储之前,可以使用此方法替换文本。 例如,拼写检查程序可能会使用此方法用正确的拼写替换拼写错误的单词。

来自apple docs https://developer.apple.com/reference/uikit/uitextviewdelegate/1618630-textview