I have use the NSTextView,and inset a image NSTextAttachment. when i select and copy it ,and then paste it,it will show pasted image in textview, but i cannot got content string from NSTextView.attributedString. why ?
3
votes
Hey, did you find a solution yet?
- Daniel
fix this by use custom type: let newContent = content.replace(String(c), new: "", mode: .literal) NSPasteboard.general().addTypes([CustomParsteFormat.Emotion], owner: nil) NSPasteboard.general().setString(newContent, forType: CustomParsteFormat.Emotion)
- user1461382
1 Answers
2
votes
I had a similar issue. Not sure if it is exactly what you want, but I wanted to be able to copy and paste an NSTextAttachment's string representation.
I ended up overriding func writeSelection(to pboard: NSPasteboard, type: String) -> Bool in my custom NSTextView class:
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
}
Note that I am using a custom NSTextAttachmentCell class that also remembers it's string representation.