我有带有表情符号的 AttributedString,如下所示“🤣🤣🤣 @Mervin tester 🤣🤣🤣”
现在我需要在这个属性字符串中找到 Mervin 的范围。
let attributedString = NSMutableAttributedString(string: "🤣🤣🤣 @Mervin tester 🤣🤣🤣")
let range = // range for "Mervin" in above String.
谢谢你。
这个扩展应该对你有帮助。
extension NSAttributedString {
func rangeOf(string: String) -> Range<String.Index>? {
return self.string.range(of: string)
}
}
用途:
attributedString.rangeOf(string: "Mervin")
我想要类似的东西,但是为了
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
}