Search code examples
swiftuitextviewuitextviewdelegate

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


im triyin to format a word from keyboard input in a 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
}

enter image description here

any ideas how to ge it done the expected result should be @yoel l


Solution

  • This will check the last word after every space for a word that has '@' in it:

    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
    }