2017-11-19 17 views
0

iOS/swift 프로젝트에서 아래 코드로 RTF 문서를 UITextView에로드하고 있습니다. RTF 자체에는 "blah blah [ABC.png] blah blah [DEF.png] blah ...와 같은 스타일의 텍스트가 포함되어 있습니다."UITextView에 잘로드되어 있습니다.Swift : 스타일이 지정된 RTF를로드 한 후 UITextView의 NSTextAttachment에 문자열 바꾸기

이제 [someImage.png]의 모든 항목을 실제 이미지로 NSTextAttachment로 대체하고 싶습니다. 어떻게해야합니까?

RTF 문서에 이미지를 포함시킬 수있는 가능성을 알고 있지만이 프로젝트에서는 할 수 없습니다.

if let rtfPath = Bundle.main.url(forResource: "testABC", withExtension: "rtf") 
{ 
    do 
    { 
    //load RTF to UITextView 
    let attributedStringWithRtf = try NSAttributedString(url: rtfPath, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) 
    txtView.attributedText = attributedStringWithRtf 

    //find all "[ABC.png]" and replace with image 
    let regPattern = "\\[.*?\\]" 
    //now...? 
    } 
} 

답변

0

다음은 사용자가 수행 할 수있는 작업입니다.

참고 : 저는 Swift Developper가 아니므로 Objective-C 코드가 더 많으므로 추악한 Swift 코드 (try! 등)가있을 수 있습니다. 그러나 메인 라인 지침 (이 CocoaTouch에서 공유이기 때문에 내가 목표 - C에서 사용) NSRegularExpression 사용에 대한 논리 그래서

에 대한 더 : 이미지의 자리가 어디
찾기.
NSAttributeString/NSTextAttachment을 작성하십시오.
자리 표시자를 이전에 귀속 된 문자열로 바꿉니다.

let regPattern = "\\[((.*?).png)\\]" 
let regex = try! NSRegularExpression.init(pattern: regPattern, options: []) 

let matches = regex.matches(in: attributedStringWithRtf.string, options: [], range: NSMakeRange(0, attributedStringWithRtf.length)) 
for aMatch in matches.reversed() 
{ 
    let allRangeToReplace = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 0)).string 
    let imageNameWithExtension = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 1)).string 
    let imageNameWithoutExtension = attributedStringWithRtf.attributedSubstring(from: aMatch.range(at: 2)).string 
    print("allRangeToReplace: \(allRangeToReplace)") 
    print("imageNameWithExtension: \(imageNameWithExtension)") 
    print("imageNameWithoutExtension: \(imageNameWithoutExtension)") 

    //Create your NSAttributedString with NSTextAttachment here 
    let myImageAttribute = ... 
    attributedStringWithRtf.replaceCharacters(in: imageNameRange, with: myImageAttributeString) 
} 

그래서 아이디어가 무엇입니까?

수정 패턴을 사용했습니다. 나는 "png"를 썼다. 그러나 당신은 그것을 바꿀 수 있었다. 재미있는 부분을 쉽게 얻기 위해 ()을 추가했습니다. .png의 유무에 관계없이 이미지의 이름을 검색하고 싶을 수 있다고 생각했기 때문에 모든 논문을 가지고 있습니다. print(). 어쩌면 앱에 저장했기 때문일 것입니다. 그룹으로 확장 프로그램을 추가해야하는 경우 regPattern에 괄호 안에 추가하고 aMatch.range(at: ??)을 호출 할 수 있습니다. for use Bundle.main.url(forResource: imageName, withExtension: imageExtension)

"match"의 길이를 다른 길이로 바꾸면 이전 범위가 꺼지기 때문에 matches.reversed()을 사용했습니다. 그래서 끝에서부터 시작하면 트릭을 할 수 있습니다.

일부 코드는 NSTextAttachment 통해 NSAttributedStringUIImage를 변환 : How to add images as text attachment in Swift using nsattributedstring