0

ゴールはNSTextViewNSAttributedStringNSImageを追加してから、プロセスを元に戻してイメージを抽出することができます。 hereのコードでは、画像を追加してインラインで表示することができます。 NSTextViewのNSTextAttachmentからNSImageをプルするにはどうすればいいですか?

let attributedText = NSMutableAttributedString(string: string, attributes: attributes as? [String : AnyObject]) 

let attachment = NSTextAttachment() 
let imageTest = NSImage(named:"sampleImage") as NSImage? 
let attachmentCell: NSTextAttachmentCell = NSTextAttachmentCell.init(imageCell: imageTest) 
attachment.attachmentCell = attachmentCell 
let imageString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) 
attributedText.append(imageString) 
textView.textStorage?.setAttributedString(attributedText) 

は限り NSTextAttachment合法的な(非ゼロ)としてこれを解体が、画像を抽出する方法が不確かなことができます。

if (textView.textStorage?.containsAttachments ?? false) { 
    let runs = textView.textStorage?.attributeRuns 
    if runs != nil { 
     for run in runs! { 
      var r = NSRange() 
      let att = run.attributes(at: 0, effectiveRange: &r) 
      let z = att[NSAttachmentAttributeName] as? NSTextAttachment 
      if z != nil { 
       Swift.print(z!) 
       // z!.image and z!.contents are both nil 
      } 
     } 
    } 
} 

ここから画像を取得する方法についてのご指摘を感謝します。ありがとうございました。

+0

からのコードの部分を置き換える私はObjective-CのとiOSでの同様のソリューションを与えた:http://stackoverflow.com/questions/29152660/extract-uiimage-from-nsattributed-stringしかし、私はそれが適用されるかもしれないと思います(多分OS Xのためのいくつかの変更で)。 – Larme

+0

iOSで 'UIImage'が動作するのはMacOSと' NSImage'では動作しません。 'image'はnilで、' imageForBounds'は空の文書アイコンのようになります。 – JKaz

+0

'z.content'に値がありますか?または、何もないプロパティがありますか? – Larme

答えて

0

NSTextAttachmentCellで作成されているため、添付のセルから取得する必要があります。キーは、セルをNSCellとしてキャストし、次にimageプロパティを取得することです。だから、元

if z != nil { 
    let cell = z!.attachmentCell as? NSCell 
    if cell != nil { 
     let image = cell?.image 
    } 
} 
関連する問題