繁体   English   中英

如何从NSAttributedString获取组件?

[英]how to get components from NSAttributedString?

我想从NSAttributedString中获取由特定字符串分隔的组件。 有可能迅速解决吗?

我可以对NSString执行此操作,但是我不确定如何对NSAttributedString执行相同操作?

因此,要解决此问题,我们需要扩展String ,以将Range转换为NSRange

extension String {
    func nsRange(fromRange range: Range<Index>) -> NSRange {
        let from = range.lowerBound
        let to = range.upperBound

        let location = characters.distance(from: startIndex, to: from)
        let length = characters.distance(from: from, to: to)

        return NSRange(location: location, length: length)
    }
}

因此输入数据。

//Input array with \n
let attributedString = NSAttributedString(string: "test string1\ntest string2\ntest string3")

//Simle String
let notAttributedString = attributedString.string

//Array of String components separated by \n
let components = notAttributedString.components(separatedBy: "\n")

比我们将要使用mapflatMap函数。 要点是对attributedSubstring(from: nsRange)用法,因为它会返回我们父级attributedString NSAttributedString ,并具有所有效果。 flatMap是因为我们的map函数返回NSAttributedString? 并且我们希望摆脱可选项。

let attributedStringArray = components.map{ item -> NSAttributedString?  in

    guard let range = notAttributedString.lowercased().range(of:item) else {
        return nil
    }

    let nsRange = notAttributedString.nsRange(fromRange: range)
    return attributedString.attributedSubstring(from: nsRange)
}.flatMap{$0}

输出:

[测试字符串1 {},测试字符串2},测试字符串3}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM