I have a NSAttributedString and want to split it at every “***“
. So in effect, I want to split a NSAttributedString everywhere where this String appeares. The result should be something like an Array of NSAttributedStrings. Thanks for your help!
You can use this extension for 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
}
}
Example`
let atributedString: NSAttributedString = NSAttributedString(string: "A***B***C***D")
let resultArray = atributedString.components(separatedBy: "***")
for atString in resultArray {
print(atString)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.