如何将NSAttributedString拆分为NSAttributedString数组

时间:2019-05-06 14:41:59

标签: swift string split nsattributedstring

我有一个NSAttributedString,想在每个“***“处进行拆分。因此,实际上,我想在出现此字符串的任何地方拆分NSAttributedString。结果应该类似于NSAttributedStrings数组。 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以将此扩展名用于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)
}