首页 > 解决方案 > 如何将 NSAttributedString 拆分为 NSAttributedString 数组

问题描述

标签: swiftstringsplitnsattributedstring

解决方案


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)
}

推荐阅读