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

时间:2018-08-07 05:46:37

标签: ios textview

例如字符串=“ 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{$0.contains(lastword)}.last
                        textView.text = myText.replacingOccurrences(of: completeLastword!, with: "")
                        return false
                    }
                }
            }
        }
    }

    return true
}

1 个答案:

答案 0 :(得分:2)

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

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

希望这会有所帮助。