简体   繁体   中英

How to replace multiple characters of UITextView text in real time with Swift?

Here are my codes:

func textViewDidChange(_ textView: UITextView) {
        if let newCharacters = newTextView.text?.enumerated() {
            for (index, item) in newCharacters {
                switch item {
                    case “1”:
                        newText.text = newTextView.text?.replacingOccurrences(of: “1”, with: “1⃣️”)
                    case “2”:
                        newText.text = newTextView.text?.replacingOccurrences(of: “2”, with: “2⃣️”)
                    case “3”:
                        newText.text = newTextView.text?.replacingOccurrences(of: “3”, with: “3⃣️”)
                default: break
                }
            }
        }
    }

Here is how it looks like:

在此处输入图片说明

But I would like to replace all the characters of the UITextView in real time, not only the last character of the text. Any ideas or suggestions would be appreciated.

The error occurs because by replacing the last character with your emoji, you are returning the previous text to the textview.

Create a variable where you store the emoji numbers and at the end, replace the text of your textview with the text of your variable.

   func textViewDidChange(_ textView: UITextView) {
    if let newCharacters = newTextView.text?.enumerated() {
        var newText = newTextView.text
        for (index, item) in newCharacters {
            switch item {
            case “1”:
                newText?.replacingOccurrences(of: “1”, with: “1⃣️”)
            case “2”:
                newText?.replacingOccurrences(of: “2”, with: “2⃣️”)
            case “3”:
                newText?.replacingOccurrences(of: “3”, with: “3⃣️”)
            default: break
            }
        }
        newTextView.text = newText
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM