在 NSMutableAttributedString 中查找子字符串的范围

问题描述 投票:0回答:2

我有带有表情符号的 AttributedString,如下所示“🤣🤣🤣 @Mervin tester 🤣🤣🤣”

现在我需要在这个属性字符串中找到 Mervin 的范围。

let attributedString = NSMutableAttributedString(string: "🤣🤣🤣 @Mervin tester 🤣🤣🤣")

let range = // range for "Mervin" in above String. 

谢谢你。

swift nsattributedstring nsrange nsmutableattributedstring
2个回答
23
投票

这个扩展应该对你有帮助。

extension NSAttributedString {
    func rangeOf(string: String) -> Range<String.Index>? {
        return self.string.range(of: string)
    }
}

用途:

attributedString.rangeOf(string: "Mervin")

0
投票

我想要类似的东西,但是为了

AttributedString
。我花了一段时间才找到解决方案,所以我想我可以在这里记录它,因为这是我的问题的第一个搜索结果。

let attributedString = AttributedString("🤣🤣🤣 @Mervin tester 🤣🤣🤣")
let substring = "Mervin"

// Iterating through all the occurrences of `substring`.
for range in attributedString.characters.ranges(of: substring) {
   // Do something with the current range
   attributedString[range].foregroundColor = .red
}
© www.soinside.com 2019 - 2024. All rights reserved.