我在UITextView中实现了hashtag识别器,但它从不突出显示具有相同开头的两个单词

时间:2016-09-18 09:06:28

标签: ios swift uitextfield uitextfielddelegate

我发现了这个问题:How to make UITextView detect hashtags?我将接受的答案复制到我的代码中。我还在我的textview中设置了delegate,然后输入了这段代码:

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

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

但是有一个奇怪的问题:它从不会突出以相同字母开头的单词。

看起来像这样:

enter image description here

这可能是什么问题?

2 个答案:

答案 0 :(得分:1)

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

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:已更新为swift 3。

答案 1 :(得分:0)

聚会晚点

    private func getHashTags(from caption: String) -> [String] {
    var words: [String] = []
    let texts = caption.components(separatedBy: " ")
    for text in texts.filter({ $0.hasPrefix("#") }) {
        if text.count > 1 {
            let subString = String(text.suffix(text.count - 1))
            words.append(subString)
        }
    }
    return words
}