我想从NSAttributedString中获取由特定字符串分隔的组件。它可能在迅速吗?如何从NSAttributedString获取组件?
我能够做到这一点的NSString,但我不知道我怎么能做到NSAttributedString相同?
我想从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")
比我们要使用map
和flatMap
功能。主要观点是使用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 {},测试STRING3 {}]
你能澄清你婉究竟是什么?这应该是可能的,但你的问题并不清楚。提取值的示例? – Larme
let attributedString:NSAttributedString = NSAttributedString(string:“test string1 \ ntest string2 \ ntest string3”)。现在我想获得由“\ n”分隔的归因字符串。 –
在Objective-C中,但应该在Swift中进行翻译:https://stackoverflow.com/questions/31250074/split-attributed-string-and-retain-formatting – Larme