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

后端 未结 2 983
遇见更好的自我
遇见更好的自我 2021-01-04 20:05

I\'m trying to create a simple NSTextView-based window for simple WYSIWYG editing. However, I only want to allow certain types of formatting (e.g. Bold, Italic, Underline a

相关标签:
2条回答
  • 2021-01-04 20:50

    [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:
    0 讨论(0)
  • 2021-01-04 21:05

    In your NSTextView subclass:

      override func paste(_ sender: Any?) {
         pasteAsPlainText(sender)
      }
    
    0 讨论(0)
提交回复
热议问题