【问题标题】:NSTextView copy paste NSTextAttachment on mac osNSTextView 在 mac os 上复制粘贴 NSTextAttachment
【发布时间】:2016-09-08 14:33:05
【问题描述】:

我使用了 NSTextView,并插入了图像 NSTextAttachment。当我选择并复制它,然后粘贴它时,它将在 textview 中显示粘贴的图像,但我无法从 NSTextView.attributedString 获取内容字符串。为什么?

【问题讨论】:

  • 嘿,你找到解决办法了吗?
  • 使用自定义类型修复这个问题: let newContent = content.replace(String(c), new: "", mode: .literal) NSPasteboard.general().addTypes([CustomParsteFormat.Emotion] , 所有者: nil) NSPasteboard.general().setString(newContent, forType: CustomParsteFormat.Emotion)

标签: cocoa nstextview


【解决方案1】:

我遇到了类似的问题。不确定它是否正是您想要的,但我希望能够复制和粘贴 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 类,该类还记得它的字符串表示形式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 2011-12-14
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多