Making URL links attributed and clickable along with editable Textview in swift

836 views Asked by At

I want to make url links clickable inside TextView as well as making that text editable just as Notes app in iPhone.

here's what I attempted:

    txtVw.dataDetectorTypes = UIDataDetectorTypes.link
    txtVw.isSelectable = true
    txtVw.isEditable = false. // this is set to false to make link text tappable
    txtVw.linkTextAttributes = [.foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue]
    txtVw.isUserInteractionEnabled = true
    txtVw.delegate = self

    let descTap = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
    descTap.numberOfTapsRequired = 1
    txtVw.addGestureRecognizer(descTap)

    @objc func textViewTapped(_: UITapGestureRecognizer) {
     txtVw.dataDetectorTypes = []
     txtVw.isEditable = true
     txtVw.becomeFirstResponder()
    }

Issue here is if I set isEditable property true, link is not formatted and remaining text if not editable. I want to achieve same things as we have in iPhone notes app. Have anyone come across this scenario? Any help would be appreciated.

1

There are 1 answers

0
Kudos On

First you need to have textView instead of Textfield. They apply below programmatic way for setting color or styling.

 let attributedString = NSMutableAttributedString(string: "I understand and agree to the Terms of Service.", attributes: [
              .font: UIFont.systemFont(ofSize: 12.0, weight: .regular),
              .foregroundColor: UIColor.errorColor,
              .kern: 0.0
            ])
            attributedString.addAttribute(.link, value: "https://policies.google.com/privacy?hl=en-US", range: NSRange(location: 30, length: 17))
            self.termOfServiceTextView.linkTextAttributes = [NSAttributedString.Key.foregroundColor.rawValue: UIColor.errorColor]
            attributedString.addAttribute(.underlineStyle, value: 1, range: NSRange(location: 30, length: 17))
            self.termOfServiceTextView.attributedText = attributedString

Now for Making it editable and clickable need to set from storyboard like: Just check Editable, Selectable options.

enter image description here