获取属性字符串中具有 url 属性的字符串的数量
Get the number of strings that have a url attribute in an attributed string
我正在尝试查找属性字符串中具有 url 属性的字符串的数量。例如,我有这样的东西:@"Hello there my name is Michael"。
name 是一个带有 url 属性 的字符串 {URL: "www.google.com"}。
我想在我的属性字符串中查找带有 url 的字符串的数量。
我尝试在我的字符串上使用 enumerateAttributes 但这只返回适用于整个字符串的属性。当我打印出我的字符串时,我可以清楚地看到有带有这个属性的字符串。我怎样才能访问它们?
你很接近。为此,您可以使用 enumerateAttribute(_:in:options:using:)
方法。您传入您感兴趣的属性(在您的情况下为 .link
),它会调用具有范围和属性值的字符串的每个子范围的闭包。这包括没有该属性的子范围。在这种情况下,nil
被传递给值。因此,要计算字符串中的链接,您需要计算 non-nil 属性:
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
}
我正在尝试查找属性字符串中具有 url 属性的字符串的数量。例如,我有这样的东西:@"Hello there my name is Michael"。
name 是一个带有 url 属性 的字符串 {URL: "www.google.com"}。
我想在我的属性字符串中查找带有 url 的字符串的数量。 我尝试在我的字符串上使用 enumerateAttributes 但这只返回适用于整个字符串的属性。当我打印出我的字符串时,我可以清楚地看到有带有这个属性的字符串。我怎样才能访问它们?
你很接近。为此,您可以使用 enumerateAttribute(_:in:options:using:)
方法。您传入您感兴趣的属性(在您的情况下为 .link
),它会调用具有范围和属性值的字符串的每个子范围的闭包。这包括没有该属性的子范围。在这种情况下,nil
被传递给值。因此,要计算字符串中的链接,您需要计算 non-nil 属性:
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
}