How to make UITextView detect hashtags?

后端 未结 4 1461
野的像风
野的像风 2021-01-31 22:39

I know that the UITextView default can detect URL, but how can i make it detect hashtags(#)?

It doesn\'t needs to detect hashtags while typing, but then

4条回答
  •  攒了一身酷
    2021-01-31 22:57

    One option would be to use an NSAttributedString, something like this...

    func convertHashtags(text:String) -> NSAttributedString {
        let attrString = NSMutableAttributedString(string: text)
        attrString.beginEditing()
        // match all hashtags
        do {
            // Find all the hashtags in our string
            let regex = try NSRegularExpression(pattern: "(?:\\s|^)(#(?:[a-zA-Z].*?|\\d+[a-zA-Z]+.*?))\\b", options: NSRegularExpressionOptions.AnchorsMatchLines)
            let results = regex.matchesInString(text,
                options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, text.characters.count))
            let array = results.map { (text as NSString).substringWithRange($0.range) }
            for hashtag in array {
                // get range of the hashtag in the main string
                let range = (attrString.string as NSString).rangeOfString(hashtag)
                // add a colour to the hashtag
                attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
            }
            attrString.endEditing()
        }
        catch {
            attrString.endEditing()
        }
        return attrString
    }
    

    Then assign your attributedText like this...

    let myText = "some text with a #hashtag in side of it #itsnoteasy"
    self.textView.attributedText = convertHashtags(myText)
    

提交回复
热议问题