Reputation: 1400
I'm trying to find the number of strings that have a url attribute in an attribute string. For example, I'd have something like this: @"Hello there my name is Michael".
name is a string with a url property like this {URL: "www.google.com"}.
I want to find the number of strings with urls in my attributed string. I tried to use enumerateAttributes over my string but this only returned attributes that apply to the whole string. When I print out my string I can clearly see that there are strings with this attribute. How can I access them?
Upvotes: 0
Views: 179
Reputation:
You’re close. For this you can use the enumerateAttribute(_:in:options:using:)
method. You pass in the attribute you are interested in (in your case .link
) and it calls the closure with each subrange of the string with the range and the value of the attribute. This includes subranges that don’t have that attribute. In this case nil
is passed for the value. So to count the links in your string you count the non-nil attributes:
func linksIn(_ attributedString: NSAttributedString) -> Int {
var count = 0
attributedString.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedString.length), options: []) { attribute, _, _ in
if attribute != nil {
count += 1
}
}
return count
}
Upvotes: 1