2017-09-25 104 views
0

我想從NSAttributedString中獲取由特定字符串分隔的組件。它可能在迅速嗎?如何從NSAttributedString獲取組件?

我能夠做到這一點的NSString,但我不知道我怎麼能做到NSAttributedString相同?

+0

你能澄清你婉究竟是什麼?這應該是可能的,但你的問題並不清楚。提取值的示例? – Larme

+0

let attributedString:NSAttributedString = NSAttributedString(string:「test string1 \ ntest string2 \ ntest string3」)。現在我想獲得由「\ n」分隔的歸因字符串。 –

+0

在Objective-C中,但應該在Swift中進行翻譯:https://stackoverflow.com/questions/31250074/split-attributed-string-and-retain-formatting – Larme

回答

0

所以要解決問題,我們需要擴展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),因爲它會返回我們的母公司attributedStringNSAttributedString以及所有效果。 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 {}]

+0

你有一個'String'數組,而不是'NSAttributedString'數組。作者似乎想要一個'NSAttributedString'數組。 – Larme

+0

@Larme正確。我想要NSAttributedString的數組。 –

+0

'NSAttributedString(string:$ 0)'這確實創建了一個NSAttributedString,但是如果最初的attributesString有特定的效果(不是默認值),那麼它就不同了。 – Larme