How to make UITextView detect hashtags?

后端 未结 4 1454
野的像风
野的像风 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 23:16

    For Swift 3 +

     extension UITextView {
            
            func convertHashtags(text:String) -> NSAttributedString {
                
                let attr = [
                    NSFontAttributeName : UIFont.systemFont(ofSize: 17.0),
                    NSForegroundColorAttributeName : clr_golden,    
                    NSLinkAttributeName : "https://Laitkor.com"
                 ] as [String : Any]
    
            
            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: NSRegularExpression.Options.anchorsMatchLines)
                let results = regex.matches(in: text,
                                                    options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, text.characters.count))
                let array = results.map { (text as NSString).substring(with: $0.range) }
                for hashtag in array {
                    // get range of the hashtag in the main string
                    let range = (attrString.string as NSString).range(of: hashtag)
                    // add a colour to the hashtag
                    //attrString.addAttribute(NSForegroundColorAttributeName, value: clr_golden , range: range)
                    attrString.addAttributes(attr, range: range)
                }
                attrString.endEditing()
            }
            catch {
                attrString.endEditing()
            }
            return attrString
        }
    }
    

    Add UITextViewDelegate in your class and Use like this

     self.tv_yourTextView.delegate = self
     self.tv_yourTextView.attributedText = tv_yourTextView.convertHashtags(text: "This is an #museer test")
    

    delegate funtion

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        print("hastag Selected!")
        return true
    }
    

    -> Modified @Wez Answer

提交回复
热议问题