如何替换iOS Swift中特定范围内的字符串?

How to replace string in particular range in iOS Swift?

例如字符串="Hello @manan123 and @man"

我正在 textview 中做标记功能,我希望当用户按退格键时,如果单词包含 @,则整个单词将删除,而不是单个字符。

但我遇到了问题,因为两个标记的词具有相同的字符。所以在上面的例子中,当我试图删除最后一个词@man 然后@manan123 也转换为 an123。

这是我在 textview 委托方法上的代码

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    if text == "" {
        if let selectedRange = textView.selectedTextRange {

            let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
            if let myText = textView.text {
                let index = myText.index(myText.startIndex, offsetBy: cursorOffset)
                let substring = myText[..<index]
                if let lastword = substring.components(separatedBy: " ").last {

                    if lastword.hasPrefix("@") {
                        //Check complete word
                        let completeLastword = myText.components(separatedBy: " ").filter{[=12=].contains(lastword)}.last
                        textView.text = myText.replacingOccurrences(of: completeLastword!, with: "")
                        return false
                    }
                }
            }
        }
    }

    return true
}

您好,我已经更新了您的代码,请检查。

if text == "" {
        if let selectedRange = textView.selectedTextRange {
            let cursorOffset = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
            if let myText = textView.text {
                let index = myText.index(myText.startIndex, offsetBy: cursorOffset)
                let substring = myText[..<index]
                if let lastword = substring.components(separatedBy: " ").last {

                    if lastword.hasPrefix("@") {
                        var newText = myText
                        let start = newText.index(myText.startIndex, offsetBy: cursorOffset - lastword.count);
                        let end = newText.index(myText.startIndex, offsetBy: (cursorOffset - lastword.count) + lastword.count);
                        newText.replaceSubrange(start..<end, with: "")
                        textView.text = newText
                        return false
                    }
                }
            }
        }
    }

希望对您有所帮助。