Search code examples
swiftnstextfieldnscellnstextattachment

Get NSImage from NSTextField in Swift


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
    ...
  }

Solution

  • 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
        ...
      }