从Swift中的NSTextField获取NSImage

时间:2014-12-05 18:13:41

标签: swift nstextfield nscell nstextattachment

我曾经从Obj-C中检索NSTextField的子类中的NSImage,如下所示:

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

当我尝试在Swift中执行相同操作时,我似乎无法转换attachmentCell但是会​​出现编译错误:

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

1 个答案:

答案 0 :(得分:1)

感谢Nate Cook。以下作品:

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