当单词以@开头时,从键盘输入中改变UITextView中的单词格式

时间:2017-11-10 21:07:10

标签: swift uitextview uitextviewdelegate

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
}

enter image description here

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

1 个答案:

答案 0 :(得分:0)

这将检查具有' @'的单词的每个空格后的最后一个单词。在其中:

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
}