2017-11-19 6 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で共有されますので、私はObjective-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: ??)を呼び出して確認してください。 Bundle.main.url(forResource: imageName, withExtension: imageExtension)

私はmatches.reversed()を使用しました。異なる長さの置換で "一致"の長さを変更すると、前の範囲はオフになるためです。だから最後からやり直すことができます。

NSTextAttachmentを通じてNSAttributedStringUIImageを変換するためのいくつかのコード:How to add images as text attachment in Swift using nsattributedstring

関連する問題