Thomas Shealy Thomas Shealy - 1 year ago 69
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() {

self.textBox.delegate = self
let text = textBox.attributedText.mutableCopy() as! NSMutableAttributedString
text.addAttribute(NSLinkAttributeName, value: "", 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: "", range: strMsg.range(of: "Terms & Condtions"))

textBox.attributedText = attrMsg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download