0

Is there a way to create a UITextView with word clickable.

When I will click on the word then word will be highlighted. Please refer below image.

effect

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
Qi Tong
  • 79
  • 2
  • 12
  • Yes it is possible but how you know which word is clickable ? – dahiya_boy Apr 26 '19 at 10:17
  • With UITapGestureRecognizer I can found the location of the tapped word, then calc the textrange, finally get the word with that textrange. I found some solutions by search "ios uitextview get tapped word" – Qi Tong Apr 26 '19 at 10:26
  • https://stackoverflow.com/questions/19779946/ios-instagram-tags-text-layout-how-is-it-done ? – Larme Apr 26 '19 at 10:26
  • https://stackoverflow.com/questions/36043006/swift-tap-on-a-part-of-text-of-uilabel – Aman Pathak Apr 26 '19 at 10:38

1 Answers1

1
     let textTest = "I have read and agree with the Privacy Policy & Terms and Conditions"

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapLabel))

    textTest.isUserInteractionEnabled = true
    textTest.addGestureRecognizer(tap)

   @IBAction func tapLabel(gesture: UITapGestureRecognizer) {

    let text = (textTest)!
    let termsRange = (text as NSString).range(of: "Terms and Conditions")
    let privacyRange = (text as NSString).range(of: "Privacy Policy")

    if gesture.didTapAttributedTextInLabel(label: attributeLabel, inRange: termsRange) {
        print("Tapped terms")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "TermsConditionViewController") as! TermsConditionViewController
        self.navigationController?.pushViewController(vc, animated: true)
    } else if gesture.didTapAttributedTextInLabel(label: attributeLabel, inRange: privacyRange) {
        print("Tapped privacy")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "PrivacyPolicyViewController") as! PrivacyPolicyViewController
        self.navigationController?.pushViewController(vc, animated: true)
    } else {
        print("Tapped none")
    }
}
Deviyani Swami
  • 749
  • 8
  • 17