One of my controllers has an NSAttributeString in which there is a link:
@IBOutlet var textView: UITextView!
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
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 linkStr
may 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, .
?