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 합법적 인 (nil이 아닌)으로 이것을 해체하지만, 이미지를 추출하는 방법을 확신 할 수 있습니다.

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

에서 코드의 부분을 대체 내가 목표 - C와 아이폰 OS에서 유사한 솔루션을 주었다 http://stackoverflow.com/questions/29152660/extract-uiimage-from-nsattributed-string하지만 나는 그것이 적용될지도 모른다고 생각한다. (어쩌면 OS X에 대한 약간의 수정으로). – Larme

+0

'UIImage'를 위해 iOS에서 작동하는 것은 MacOS와'NSImage'에서는 작동하지 않습니다. 'image'는 nil이고'imageForBounds'는 빈 문서 아이콘처럼 보이는 것을 반환합니다. – JKaz

+0

'z.content'에 값이 있습니까? 아니면 아무 것도없는 부동산이 있습니까? – Larme

답변

0

NSImageNSTextAttachmentCell으로 작성되었으므로 첨부 셀에서 검색해야합니다. 핵심은 셀을 NSCell으로 캐스팅 한 다음 image 속성을 가져 오는 것입니다. 그래서, 원래

if z != nil { 
    let cell = z!.attachmentCell as? NSCell 
    if cell != nil { 
     let image = cell?.image 
    } 
}