当单词以@开头时,从键盘输入更改文本视图中的单词格式

changin a word format in UITextView from keyboard input when the word begins with @

im triyin 格式化来自 uitextfield 中键盘输入的单词,

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


    let words = textView.text.components(separatedBy: " ")
    for word in words{
        if word.hasPrefix("@"){
            let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
            let attributedString = NSMutableAttributedString(string: word, attributes: attributes)
            self.textView.textStorage.insert(attributedString, at: range.location)
            let cursor =  NSRange(location: self.textView.selectedRange.location+1, length: 0) //textView.text.range(of: word)
            textView.selectedRange = cursor
            return true
        }
    }

    return true
}

任何关于如何完成它的想法 预期结果应该是 @yoel l

这将检查每个 space 之后的最后一个单词是否包含“@”:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
     if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.contains("@"), let lastWordRange = (textView.text as? NSString)?.range(of: lastWord){
         let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
         let attributedString = NSMutableAttributedString(string: lastWord, attributes: attributes)
         textView.textStorage.replaceCharacters(in:lastWordRange, with:attributedString)
     }
     return true
}