특정 문자열로 구분 된 구성 요소를 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
을 반환하기 때문입니다. map
함수가 NSAttributedString?
을 반환하고 optionals을 제거하고자하므로 flatMap
이 사용되었습니다.
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
하자 attributedString : NSAttributedString = NSAttributedString (문자열 : "test string1 \ ntest string2 \ ntest string3"). 이제 "\ n"으로 구분 된 속성 문자열을 가져 오려고합니다. –
Objective-C에서 Swift로 번역해야 함 : https://stackoverflow.com/questions/31250074/split-attributed-string-and-retain-formatting – Larme