簡體   English   中英

如何使用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的所有字符,而不僅僅是文本的最后一個字符。 任何想法或建議,將不勝感激。

發生錯誤的原因是,通過用表情符號替換最后一個字符,您會將前一個文本返回到textview。

創建一個用於存儲表情符號編號的變量,最后將textview的文本替換為變量的文本。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM