I'm trying to handle a paste operation on a NSTextField
.
I found a similar article but for NSTextView
. I tried code similar to this by overriding NSTextField
and putting:
- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
{
return [super readSelectionFromPasteboard: pboard];
}
But this method seems to never be called.
Any suggestions on how to detect a past on NSTextField?
You could use the NSTextFieldDelegate
delegate method - (BOOL) control:(NSControl*) control textView:(NSTextView*) textView doCommandBySelector:(SEL) commandSelector
and watch for the paste:
selector.
Override the becomeFirstResponder
method of your NSTextField
Use object_setClass
to override the class of the "field editor" (which is the NSTextView
that handles text input for all NSTextField
instances; see here)
#import <AppKit/AppKit.h>
#import <objc/runtime.h>
@interface MyTextField : NSTextField
@end
@implementation MyTextField
- (BOOL)becomeFirstResponder
{
if ([super becomeFirstResponder]) {
object_setClass(self.currentEditor, MyFieldEditor.class);
return YES;
}
return NO;
}
@end
MyFieldEditor
class and override its paste:
method@interface MyFieldEditor : NSTextView
@end
@implementation MyFieldEditor
- (void)paste:(id)sender
{
// Get the pasted text.
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSString *text = [pasteboard stringForType:NSPasteboardTypeString];
NSLog(@"Pasted: %@", text);
// Set the pasted text. (optional)
[pasteboard clearContents];
[pasteboard setString:@"Hello world" forType:NSPasteboardTypeString];
// Perform the paste action. (optional)
[super paste:sender];
}
@end
All done! Now you can intercept every paste action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With