cocoa - NSTextView 在 mac os 上复制粘贴 NSTextAttachment

标签 cocoa nstextview

我使用了 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/

相关文章:

swift - OSX swift : Editor placeholder in sourcefile error on NSTextView

objective-c - NSTextView 不会更新,除非我点击它,并且它不会聚焦。有任何想法吗?

cocoa - 动画菜单项

ios - 顺序后台获取请求 iOS 7

html - 将带有 CSS 的 HTML 放入 NSTextView 的简单示例?

swift - 检测到 NSTextView 缺少约束

objective-c - [NSRegularExpression stringByReplacingMatchesInString] 的意外行为

cocoa - 开始使用适用于 OS X 的 Cocoa?

macos - 适用于 OS X 的 ABAddressBook/ABSource

macos - 如何在 NSTextView 中禁用这些键盘快捷键?