问题
I am using UITextView and implemented the delegate function
var count = 0
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print(text)
count += 1
print(count)
return true
}
sample
When i select the predictive text from the Keyboard, shouldChangeTextInRange delegate is calling twice.
- Why this delegate calling twice?
- Why this happening with predictive text alone
回答1:
Please use this code. It will work fine and hope It will be perfectly working with your existing logic.
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
}
Answer for both question 1 and 2 is When you select text from the predictive text. First, it appends word then It appends a space. That's the reason delegate is called twice.
回答2:
The text view calls this method whenever the user types a new character or deletes an existing character. Implementation of this method is optional. You can use this method to replace text before it is committed to the text view storage. For example, a spell checker might use this method to replace a misspelled word with the correct spelling.
from apple docs https://developer.apple.com/reference/uikit/uitextviewdelegate/1618630-textview
来源:https://stackoverflow.com/questions/41635581/uitextview-delegate-calling-multiple-times