0

I found this question: I'm implementing a hashtag recognizer in UITextView but it never highlights two words with the same beginning?. By doing that I want to check the user's run time input text on the text view and each time user types a #hashtag, It will automatically highlight after adding a comma.

Code:-

import UIKit

class ViewController: UIViewController,UITextViewDelegate {

@IBOutlet weak var txtView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    txtView.delegate = self
}

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

extension UITextView {
func resolveHashTags() {
    let nsText = NSString(string: self.text)
    let words = nsText.components(separatedBy: CharacterSet(charactersIn: "#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_").inverted)
    let attrString = NSMutableAttributedString()
    attrString.setAttributedString(self.attributedText)
    for word in words {
        if word.count < 3 {
            continue
        }
        if word.hasPrefix("#") {
            let matchRange:NSRange = nsText.range(of: word as String)
            let stringifiedWord = word.dropFirst()
            if let firstChar = stringifiedWord.unicodeScalars.first, NSCharacterSet.decimalDigits.contains(firstChar) {
            } else {
                attrString.addAttribute(NSAttributedString.Key.link, value: "hash:\(stringifiedWord)", range: matchRange)
            }
        }
      }
    self.attributedText = attrString
   }
}

Current ScreenShot:-

Image

Question:- Can someone please explain to me how to highlight the text after adding a comma? I've tried to implement by above code but no results yet.

Any help would be greatly appreciated.

Thanks in advance.

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59

0 Answers0