2017-09-25 5 views
0

특정 문자열로 구분 된 구성 요소를 NSAttributedString에서 가져 오려고합니다. 신속하게 가능합니까?NSAttributedString에서 구성 요소를 가져 오는 방법은 무엇입니까?

NSString에 대해이 작업을 수행 할 수 있지만 NSAttributedString에 대해 어떻게 동일한 작업을 수행 할 수 있는지 잘 모르겠습니다.

+0

당신이 정확히 완 무엇인지 명확히 수 있을까? 가능해야하지만 질문이 명확하지 않습니다. 값을 추출한 예는 무엇입니까? – Larme

+0

하자 attributedString : NSAttributedString = NSAttributedString (문자열 : "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)의 사용이며 모든 효과가있는 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 {}]

+0

'NSAttributedString'의 배열이 아닌'String' 배열을 가지고 있습니다. 그리고 저자는'NSAttributedString' 배열을 원한다고합니다. – Larme

+0

@Larme correct. 나는 NSAttributedString의 배열을 원한다. –

+0

'NSAttributedString (string : $ 0)'이것은 실제로 NSAttributedString을 만들지 만 초기 attributedString이 특정 효과 (기본값이 아님)가있는 경우에는 다릅니다. – Larme