swift - 在 Swift 中从 NSTextField 获取 NSImage

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

最佳答案

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

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

关于swift - 在 Swift 中从 NSTextField 获取 NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322169/

相关文章:

ios - 单击单元格中的按钮时如何解析以播放某首歌曲?

objective-c - NSTextField 自动完成方法

cocoa - 如何通过绑定(bind)在弹出按钮中选择名字的文本字段中显示用户的姓氏

image - 使用 Swift 创建随机图像生成器

ios - 侧面菜单,以编程方式隐藏菜单选项

macos - 如何以编程方式使标签(NSTextField)按内容自动调整大小?

cocoa - 让 NSFormatter 持续验证 NSTextFieldCell

swift - 如何不在 NSCellTextView Swift 5 中截断文本

swift - 如何允许粘贴(cmd+v)到 NSTableView 单元格中?

ios - 如何为自定义单元格内的按钮设置监听器以快速获取文本字段数据?