【问题标题】:changin a word format in UITextView from keyboard input when the word begins with @当单词以@开头时,从键盘输入更改 UITextView 中的单词格式
【发布时间】:2017-11-10 21:07:10
【问题描述】:

我在 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

【问题讨论】:

  • 它看起来对您有用 - 请描述您遇到的确切问题?
  • 想要的结果应该是蓝色的@yoel,其余的应该是黑色
  • 要清楚 - 您在文本字段中输入了“@yoel”,上面是您返回的内容?
  • 我输入了这是一个字符串@yoel l,但我看到的是@@y@o@e@l@y@y 每个键输入重复@并按下键

标签: swift uitextview uitextviewdelegate


【解决方案1】:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多