如何用Swift实时替换UITextView文本的多个字符?

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

这是我的代码:

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
                }
            }
        }
    }

这是它的样子:

但我想实时替换 UITextView 的所有字符,而不仅仅是文本的最后一个字符。如有任何想法或建议,我们将不胜感激。

发生此错误是因为用表情符号替换最后一个字符,会将之前的文本返回到文本视图。

创建一个存储表情符号编号的变量,最后,将文本视图的文本替换为变量的文本。

   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
    }
}