UITextView delegate calling multiple times

会有一股神秘感。 提交于 2019-12-12 12:19:24

问题


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.

  1. Why this delegate calling twice?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!