我在UITextView中实现hashtag识别器,但它永远不会突出显示两个字开头相同

问题描述:

我发现这个问题:How to make UITextView detect hashtags?我将接受的答案复制到我的代码中。我还设置了delegate我的TextView,然后把这个代码:我在UITextView中实现hashtag识别器,但它永远不会突出显示两个字开头相同

func textViewDidChange(textView: UITextView) { 
    textView.resolveHashTags() 
} 

通过这样做,我想检查TextView的,每次用户键入#hashtag用户的输入 - 我会自动突出显示。

但有一个奇怪的问题:它从不强调以相同字母开头的单词。

它看起来像这样:

enter image description here

什么也许这里是什么问题?

+0

你可能会喜欢看https://github.com/optonaut/ActiveLabel.swift我用这个在最近的一个项目中,它工作得很好。 – Sarcoma

+0

@Sarcoma谢谢,但它不适用于输入文本视图,所以这就是我没有使用它的原因... – user3766930

+0

我明白你想要做什么,我实际上写了一个脚本来做到这一点,但用@name提到。尽管如此,我还没有这样做。 – Sarcoma

func resolveHashTags(text : String) -> NSAttributedString{ 
    var length : Int = 0 
    let text:String = text 
    let words:[String] = text.separate(withChar: " ") 
    let hashtagWords = words.flatMap({$0.separate(withChar: "#")}) 
    let attrs = [NSFontAttributeName : UIFont.systemFont(ofSize: 17.0)] 
    let attrString = NSMutableAttributedString(string: text, attributes:attrs) 
    for word in hashtagWords { 
     if word.hasPrefix("#") { 
       let matchRange:NSRange = NSMakeRange(length, word.characters.count) 
       let stringifiedWord:String = word 

       attrString.addAttribute(NSLinkAttributeName, value: "hash:\(stringifiedWord)", range: matchRange) 
     } 
     length += word.characters.count 
    } 
    return attrString 
} 

分隔单词我用一个字符串扩展

extension String { 
    public func separate(withChar char : String) -> [String]{ 
    var word : String = "" 
    var words : [String] = [String]() 
    for chararacter in self.characters { 
     if String(chararacter) == char && word != "" { 
      words.append(word) 
      word = char 
     }else { 
      word += String(chararacter) 
     } 
    } 
    words.append(word) 
    return words 
} 

} 

我希望这是你在找什么。告诉我它是否适合你。

编辑:

func textViewDidChange(_ textView: UITextView) { 
     textView.attributedText = resolveHashTags(text: textView.text) 
     textView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.red] 
    } 

编辑2:更新了迅速3.

+0

感谢人,并对延迟回复感到抱歉...你能告诉我如何使用它在textview中实时突出显示单词吗? – user3766930

+0

我更新了答案。 – unniverzal