Get NSImage from NSTextField in Swift

349 views Asked by At

I used to retrieve the NSImage in a subclass of NSTextField from Obj-C like this:

  NSDictionary *attributedVal = [[self attributedStringValue] attributesAtIndex:i effectiveRange:&effectiveRange];
  if ([[attributedVal allKeys] containsObject:NSAttachmentAttributeName]) {
    NSTextAttachment *attachment = [attributedVal valueForKey:NSAttachmentAttributeName];
    NSCell *attachmentCell = (NSCell *)[attachment attachmentCell];
    ... [[attachmentCell image] name] ...
  } 

When I try to do the same in Swift I can't seem to be able to cast attachmentCell but get a compiler error:

  let attributedVal = attributedStringValue.attributesAtIndex(i, effectiveRange: effectiveRange)
  if let attachment = attributedVal[NSAttachmentAttributeName] as? NSTextAttachment {
    let attachmentCell = attachment.attachmentCell as NSCell // does not work
    ...
  }
1

There are 1 answers

0
qwerty_so On BEST ANSWER

Thanks to Nate Cook. The following works:

  let attributedVal = attributedStringValue.attributesAtIndex(i, effectiveRange: effectiveRange)
  if let attachment = attributedVal[NSAttachmentAttributeName] as? NSTextAttachment {
    let attachmentCell = attachment.attachmentCell as NSTextAttachmentCell
    let image = attachmentCell.image
    ...
  }