Thomas Shealy Thomas Shealy - 5 months ago 18
Swift Question

(Swift) adding hyperlink to a small amount of characters over a huge string in a TextView

I'm essentially cloning some pages out of a website into UITextViews. I have them set to attributed text so when I paste the text from the website, it retains it's sizes and fonts. However, many of the pages contain hyperlinked words (like "click here") which are not recognized as links.

I've tried pulling the text from the text view (I'm pasting into the storyboard), converting it to an NSMutableAttributedString, adding the hyperlink as an attribute over a range, then converting back to an NSAttributedString and setting that as the text for the TextView. Problem is, the range is weird. For example here's what a range from 0-5 looks like (look at top left):
Range from 0-5
and at a range of 8-10 Range from 8-10
I need it to apply to the "'What can I do now to help?'". Any suggestions on how to make this work would be greatly appreciated. Here is my code:

import UIKit

class ApproachController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textBox: UITextView!

override func viewDidLoad() {
super.viewDidLoad()

self.textBox.delegate = self
let text = textBox.attributedText.mutableCopy() as! NSMutableAttributedString
text.addAttribute(NSLinkAttributeName, value: "https://campushealth.unc.edu/services/counseling-and-psychological-services/how-support-student-distress/what-can-i-do-right-now", range: NSMakeRange(8, 10))
self.textBox.attributedText = text.copy() as! NSAttributedString
}

Answer Source

You can specify use range of substring like:

    let strMsg : NSString = "By registering you agree to our Terms & Condtions & Privacy Policy" - Replace this with your textBox.text

    attrMsg.addAttribute(NSLinkAttributeName, value: "http://www.seqlegal.com/free-legal-documents/website-terms-and-conditions", range: strMsg.range(of: "Terms & Condtions"))

textBox.attributedText = attrMsg