我使用了NSTextView,并插入了图像NSTextAttachment。当我选择并复制它,然后粘贴它,它将在textview中显示粘贴的图像,但我无法从NSTextView.attributedString获取内容字符串。为什么?
答案 0 :(得分:2)
我有类似的问题。不确定它是否正是您想要的,但我希望能够复制并粘贴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类,它也会记住它的字符串表示形式。