2

我曾经从 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
    ...
  }
4

1 回答 1

1

感谢内特库克。以下作品:

  let attributedVal = attributedStringValue.attributesAtIndex(i, effectiveRange: effectiveRange)
  if let attachment = attributedVal[NSAttachmentAttributeName] as? NSTextAttachment {
    let attachmentCell = attachment.attachmentCell as NSTextAttachmentCell
    let image = attachmentCell.image
    ...
  }
于 2014-12-05T21:03:28.203 回答