咨询:统计富文本字符串中带URL属性的子串数量
统计NSAttributedString中带URL属性的子串数量
嘿,我懂你的困扰!你之前用enumerateAttributes没拿到想要的结果,大概率是调用时的细节没处理对——这个方法其实完全可以帮你遍历到所有带URL属性的子串范围,只是得用对方式。
问题根源
你说方法只返回适用于整个字符串的属性,可能是你构造富文本时不小心把URL属性加到了整个字符串上,或者调用enumerateAttributes时没正确遍历所有子范围。咱们用你给的例子来实际操作一遍:
正确实现代码
首先构造符合你描述的富文本(只有"name"带URL属性),然后用enumerateAttributes遍历统计:
// 1. 构造目标富文本 let baseText = "Hello there my name is Michael" let mutableAttributedText = NSMutableAttributedString(string: baseText) // 给"name"添加URL属性 if let nameRange = baseText.range(of: "name") { let nsRange = NSRange(nameRange, in: baseText) mutableAttributedText.addAttribute( .link, value: URL(string: "www.google.com")!, range: nsRange ) } // 2. 统计带URL属性的子串数量 var urlSubstringCount = 0 mutableAttributedText.enumerateAttributes( in: NSRange(location: 0, length: mutableAttributedText.length), options: [] ) { attributes, range, stop in // 检查当前范围是否包含URL属性 if attributes[.link] != nil { urlSubstringCount += 1 // 可选:打印子串和范围,方便验证 let substring = mutableAttributedText.attributedSubstring(from: range) print("找到带URL的子串:\(substring.string),范围:\(range)") } } print("最终统计数量:\(urlSubstringCount)")
关键说明
enumerateAttributes会自动把连续拥有相同属性集合的字符串片段作为一个遍历项返回。如果你的富文本里有多个不连续的带URL的子串(比如"name"和"Michael"都加了URL),这个方法会分别计数,结果就是2。- 如果你的需求是统计不同的URL地址数量(而不是子串个数),可以把遍历到的URL存到
Set<URL>里,最后取集合的count即可。
内容的提问来源于stack exchange,提问作者MichaelGofron
相关产品推荐
相关产品推荐

