Search code examples
iosobjective-cuitextfieldtouch

How to know when text is copied from a specific textfield in Objective-C?


I have some textFields which are editable. when user selects its text copy and paste menu items are shown.
I want to know when user taps on the copy. because I want to change the copied text.
Is it possible?

More details: I want to change the copy of 3 textfields. I want to concatenate all these 3 textfields texts into clipboard when one of the textfields are copied. There are other textfields in this page too but I don't want to do anything for them.


Solution

  • You can implement the copy() method to "intercept" the copy operation and modify what gets placed on the clipboard.

    Easiest way is probably a simple subclass of UITextField:

    //
    //  MyTextField.h
    //
    //  Created by Don Mag on 5/29/19.
    //
    
    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface MyTextField : UITextField
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    and

    //
    //  MyTextField.m
    //
    //  Created by Don Mag on 5/29/19.
    //
    
    #import "MyTextField.h"
    
    @implementation MyTextField
    
    - (void)copy:(id)sender {
    
        // debugging
        NSLog(@"copy command selected");
    
        // get the selected range
        UITextRange *textRange = [self selectedTextRange];
    
        // if text was selected
        if (textRange) {
    
            // get the selected text
            NSString *selectedText = [self textInRange:textRange];
    
            // change it how you want
            NSString *modifiedText = [NSString stringWithFormat:@"Prepending to copied text: %@", selectedText];
    
            // get the general pasteboard
            UIPasteboard *pb = [UIPasteboard generalPasteboard];
    
            // set the modified copied text to the pasteboard
            pb.string = modifiedText;
        }
    
    }
    
    @end