1

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
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Why not use webviews instead? – Sweeper May 12 '17 at 06:06
  • 1
    Possible duplicate of [How to create Hyperlink on particular textView text in ios](http://stackoverflow.com/questions/43907582/how-to-create-hyperlink-on-particular-textview-text-in-ios) – Ketan Parmar May 12 '17 at 06:30

2 Answers2

1

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
user3575114
  • 993
  • 7
  • 13
1

With user3575114's help, I got it working. Here's my corrected code incase anyone is having the same issue:

override func viewDidLoad() {
    super.viewDidLoad()

    self.textBox.delegate = self

    let strang = textBox.text! as NSString

    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: strang.range(of: "What can I do now to help?"))

    textBox.attributedText = text
}