Skip to content

Instantly share code, notes, and snippets.

Last active December 25, 2015 23:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Knowing the nature of text changes, helps to deal with it better.

Change type enumeration

typedef NS_ENUM(NSUInteger, SZSTextChangeType) {

We can use following method to determine a nature of changes. Following is based on reference for textView:shouldChangeTextInRange:replacementText:

static inline SZSTextChangeType SZSTextChangeTypeFromRangeText(NSRange range, NSString *text) {
	if (![text length]) {
		return SZSTextChangeTypeDelete;
	} else if (!range.length) {
		return SZSTextChangeTypeInsert;
	return SZSTextChangeTypeReplace;
 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
	SZSTextChangeType change = SZSTextChangeTypeFromRangeText(range, text);
	NSRange newSelectionRange;
	switch (change) {
		case SZSTextChangeTypeDelete: {
			NSString *stringToBeRemoved = [textView.text substringWithRange:range];
			newSelectionRange = NSMakeRange(range.location, 0);
		case SZSTextChangeTypeInsert: {
			NSString *stringToBeInserted = text;
			newSelectionRange = NSMakeRange(textView.selectedRange.location + [text length], 0);
		case SZSTextChangeTypeInsert: {
			NSString *stringToBeReplaced = [textView.text substringWithRange:range];
			newSelectionRange = NSMakeRange(textView.selectedRange.location, textView.selectedRange.length + [text length]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment