How can you intercept pasting into a NSTextView to remove unsupported formatting?

拜拜、爱过 提交于 2019-12-01 04:03:29

In your NSTextView subclass:

  override func paste(_ sender: Any?) {
     pasteAsPlainText(sender)
  }

[Edit: see Joshua Nozzi's comment!]

One possible solution would be to make your NSTextView implement this template method:

- (void)paste:(id)sender {
    NSPasteboard *pb = [NSPasteboard generalPasteboard];
    //receive formatted string from pasteboard
    //remove formatting from string
    //put back plaintext string into pasteboard
    [super paste:sender];
    //put back initial formatted string
}

This way you don't have to handle any of the actual insertion/pasting but can mess with the pasteboard before the actual pasting.

You might also want to look into these methods of NSTextView dealing with the Pasteboard:

  • preferredPasteboardTypeFromArray:restrictedToTypesFromArray:
  • readSelectionFromPasteboard:
  • readSelectionFromPasteboard:type:
  • readablePasteboardTypes
  • writablePasteboardTypes
  • writeSelectionToPasteboard:type:
  • writeSelectionToPasteboard:types:
  • validRequestorForSendType:returnType:
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!