5

I am having issues getting a NSTextAttachment image to work in a NSTextView for an OS X application.

The image of the NSTextAttachment is just not displayed at all. However, it still seems to be set correctly. Because when copying the contents of the NSTextView and pasting it back into e.g. TextEdit.app, the pasted text contains the image correctly.

Here is a minimal playground reproducing the issue:

import Cocoa

let img = NSImage(named: "Checked")

let textView = NSTextView(frame: NSMakeRect(0, 0, 254, 64))

let attrstr = NSMutableAttributedString(string: "Test")

let attch = NSTextAttachment()
attch.image = img

attrstr.appendAttributedString(NSAttributedString(attachment: attch))

textView.textStorage!.setAttributedString(attrstr)

textView

enter image description here

Expected output:

enter image description here

For iOS, so using UIKit instead of Cocoa, it works perfectly fine:

import UIKit

let img = UIImage(named: "Checked")

let textView = UITextView(frame: CGRectMake(0.0, 0.0, 200.0, 44.0))

let attrstr = NSMutableAttributedString(string: "Test")

let attch = NSTextAttachment()
attch.image = img

attrstr.appendAttributedString(NSAttributedString(attachment: attch))

textView.attributedText = attrstr

textView

enter image description here

I am using XCode 7. Both playgrounds can be downloaded here.

Any idea is highly welcome, Thanks in advance!

rkusa
  • 4,792
  • 1
  • 22
  • 28

1 Answers1

7
var thumbnailImage: NSImage? = // some image
var attachmentCell: NSTextAttachmentCell = NSTextAttachmentCell.initImageCell(thumbnailImage!)
var attachment: NSTextAttachment = NSTextAttachment()
attachment.attachmentCell = attachmentCell
var attrString: NSAttributedString = NSAttributedString.attributedStringWithAttachment(attachment)
self.textView.textStorage().appendAttributedString(attrString)
rocky
  • 3,521
  • 1
  • 23
  • 31
  • Thanks, works perfectly fine! I really appreciate it! – rkusa Mar 21 '16 at 20:42
  • Thanks! Do you know how to provide drag & drop with the image of the cell? By default if I drag it to Finder it creates an empty text file – hyouuu Nov 09 '18 at 02:18