我使用了 NSTextView,并插入了图像 NSTextAttachment。当我选择并复制它,然后粘贴它时,它将在 TextView 中显示粘贴的图像,但我无法从 NSTextView.attributedString 获取内容字符串。为什么?
最佳答案
我也有类似的问题。不确定它是否正是您想要的,但我希望能够复制并粘贴 NSTextAttachment 的字符串表示形式。
我最终在我的自定义 NSTextView 类中重写了 func writeSelection(to pboard: NSPasteboard, type: String) -> Bool
:
override func writeSelection(to pboard: NSPasteboard, type: String) -> Bool {
let selectedAttributedString = attributedString().attributedSubstring(from: selectedRange())
let selectedAttributedStringCopy = NSMutableAttributedString(attributedString: selectedAttributedString)
selectedAttributedStringCopy.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0,(selectedAttributedString.string.characters.count)), options: .reverse, using: {(_ value: Any?, _ range: NSRange, _ stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let textAttachment = value as? NSTextAttachment, let textAttachmentCell = textAttachment.attachmentCell as? YouCustomTextAttachmentCellClass {
var range2: NSRange = NSRange(location: 0,length: 0)
let attributes = selectedAttributedStringCopy.attributes(at: range.location, effectiveRange: &range2)
selectedAttributedStringCopy.replaceCharacters(in: range, with: NSMutableAttributedString(string: textAttachmentCell.yourStringRepresentation))
selectedAttributedStringCopy.addAttributes(attributes, range: range)
// selectedAttributedStringCopy.insert(attachmentAttributedString, at: range.location)
}
})
pboard.clearContents()
pboard.writeObjects([selectedAttributedStringCopy])
return true
}
请注意,我使用的是自定义 NSTextAttachmentCell 类,它还记住它的字符串表示形式。
关于cocoa - NSTextView 在 mac os 上复制粘贴 NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39393701/