简体   繁体   English

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

[英]How to replace string in particular range in iOS Swift?

For example string = "Hello @manan123 and @man" 例如,字符串=“ Hello @ manan123 and @man”

i am doing tagging functionality in textview and i want when user press backspace if word contains @ then whole word will delete not single character. 我正在做textview中的标记功能,我想当用户按退格键(如果单词包含@)时,整个单词将不会删除单个字符。

but i am facing problem while two tagged word have same characters. 但是当两个标记的单词具有相同的字符时,我面临问题。 So in above example when i am trying to delete last word @man then @manan123 also convert to the an123. 因此,在上面的示例中,当我尝试删除最后一个单词@man时,@ manan123也将转换为an123。

Here is my code on textview delegate method 这是我关于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
}

Hi I have updated your code please check it. 嗨,我已经更新了您的代码,请检查一下。

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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