我正在使用 UITextView 并实现了委托(delegate)功能
var count = 0
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print(text)
count += 1
print(count)
return true
}
样本
当我从键盘选择预测文本时,shouldChangeTextInRange 委托(delegate)调用了两次。
- 为什么这个代表打电话两次?
- 为什么单独使用预测文本会发生这种情况
最佳答案
请使用此代码。它会很好地工作,希望它能完美地与您现有的逻辑一起工作。
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/