Swift 3: Getting substring attributes in NSAttributedString

One of my controllers has an NSAttributeString in which there is a link:

@IBOutlet var textView: UITextView!

// Below is extracted from viewDidLoad()
let linkStr = "Click <a href='http://google.com'>here</a> for good times."
let attributedText = try! NSAttributedString(
  data: linkStr.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
  options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
  documentAttributes: nil)
textView.attributedText = attributedText

I am writing a unit test for a controller, and I want to check if the link to the text "here" is correct. (The link is really generated dynamically, so I want to test it).

Anyway, I can obviously get a non-attribute text as follows:

let text = viewController.textView.attributedText.string
// text == "Click here for good times."

I can also get the link attribute from "here" by doing something like this:

let url = uviewController.textView.attributedText.attribute(
    "NSLink", at: 6, effectiveRange: nil)
// url == A URL object for http://google.com.

The problem is that I had to hardcode "6" for the parameter at. The value linkStrmay change in the future, and I do not want to update my test every time. In this case, we can assume that he will always have the word "here" with a link attached to this word.

, "" linkStr at, NSLink URL. , Swift, .

?

+6
1

hardcoding. Swift 3 :

import UIKit
import PlaygroundSupport

let linkStr = "Click <a href='http://google.com'>here</a> for good times."
let attributedText = try! NSAttributedString(
    data: linkStr.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
    documentAttributes: nil)

attributedText.enumerateAttribute(NSLinkAttributeName , in: NSMakeRange(0, attributedText.length), options: [.longestEffectiveRangeNotRequired]) { value, range, isStop in
    if let value = value {
        print("\(value) found at \(range.location)")
    }
}

print :

http://google.com/ found at 6
+5

Source: https://habr.com/ru/post/1016531/


All Articles