[英]Get NSAttributedString from UITextField within NSRange
[英]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")
比我們將要使用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},測試字符串3}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.