how to know when text is pasted into UITextView how to know when text is pasted into UITextView xcode xcode

how to know when text is pasted into UITextView


Here is what i use to detect paste events in UITextView:

 // Set this class to be the delegate of the UITextView. Now when a user will paste a text in that textview, this delegate will be called.-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {    // Here we check if the replacement text is equal to the string we are currently holding in the paste board    if ([text isEqualToString:[UIPasteboard generalPasteboard].string]) {        // code to execute in case user is using paste    } else {        // code to execute other wise    }    return YES;}


Checking the pasteboard's string by if string == UIPasteboard.general.string takes a couple of seconds if you have long sentence in the pasteboard. The user sees the keypad is frozen while this check. My solution is to check if the length of new characters is longer than 1. If it is longer than 1, the string is from the pasteboard.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {        if string.characters.count > 1{            //User did copy & paste        }else{            //User did input by keypad        }                     return true }


Your UITextView will call its UITextViewDelegate method

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

if a delegate has been set up. This gets called both when a character is typed on the keyboard, and when text is pasted into the text view. The text pasted in is the replacementText argument.

See http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html#//apple_ref/occ/intf/UITextViewDelegate