我想從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