Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextAttachment image not shown in NSTextView (but in UITextView)?

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!

like image 736
rkusa Avatar asked Mar 19 '16 18:03

rkusa


1 Answers

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)
like image 107
rocky Avatar answered Nov 15 '22 09:11

rocky