2017-09-25 44 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