Group Group Group Group Group Group Group Group Group

Multiple HyperLinks in TextView


I am trying to have multiple hyperlinks within a TextView using dataDetectors and attributedStrings, but I am only able to get one at a time. I am sure that I am missing something, but cannot think of what…

Basically, I can get only one link working at a time.

Here’s the sample code that I am using:
extension NSAttributedString {
static func makeHyoerLink(for path: String, in string: String, as substring: String) -> NSAttributedString {

    let nsString = NSString(string: string)
    let subStringRange = nsString.range(of: substring)
    let attributedString = NSMutableAttributedString(string: string)
    attributedString.addAttribute(.link, value: path, range: subStringRange)
    return attributedString

Then calling the following method:

private func configureHyperLink(link: String, key: String) -> NSAttributedString {

    textView.dataDetectorTypes = .all
    textView.font = UIFont.preferredFont(forTextStyle: .body)
    textView.isEditable = false 
    textView.isSelectable = true
    textView.isUserInteractionEnabled = true
    textView.dataDetectorTypes = .link
    textView.backgroundColor = .systemBackground
    let path = link

    let attrivbutedString = NSAttributedString.makeHyoerLink(for: path, in: textView.text, as: key)
    return attrivbutedString

let font = textView.font
let color = textView.textColor
textView.attributedText = configureHyperLink(link: “”, key: “life”)
textView.text = str1 + “Test the news”
textView.font = font
textView.textColor = color

Thanks for your help.

I was able to solve the issue. I had to the following in case anyone else will run into the same problem.

  1. Create a NSMutableAttributedString string with the text that I want in the textView field.
  2. add two or more attributedString.addAttribute with unique values.
  3. Implement UITextViewDelegate with the method: textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange:…
  4. From within the method, determine URL.absoluteString was equal to the unique value that I set in step #2.

Glad you were able to solve the issue @plemelle! Thanks for sharing your solution :smile:.