gpt4 book ai didi

swift - 如何将 NSAttributedString 拆分为 NSAttributedString 数组

转载 作者:行者123 更新时间:2023-11-30 10:44:38 26 4
gpt4 key购买 nike

我有一个 NSAttributedString 并希望在每个 “***” 处拆分它。所以实际上,我想在该字符串出现的任何地方分割一个 NSAttributedString 。结果应该类似于 NSAttributedStrings 数组。感谢您的帮助!

最佳答案

您可以将此扩展用于 NSAttributedString

private extension NSAttributedString {
func components(separatedBy separator: String) -> [NSAttributedString] {
var result = [NSAttributedString]()
let separatedStrings = string.components(separatedBy: separator)
var range = NSRange(location: 0, length: 0)
for string in separatedStrings {
range.length = string.count
let attributedString = attributedSubstring(from: range)
result.append(attributedString)
range.location += range.length + separator.count
}
return result
}
}

示例`

let atributedString: NSAttributedString = NSAttributedString(string: "A***B***C***D")
let resultArray = atributedString.components(separatedBy: "***")
for atString in resultArray {
print(atString)
}

关于swift - 如何将 NSAttributedString 拆分为 NSAttributedString 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com