Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zats
Last active December 25, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zats/7060237 to your computer and use it in GitHub Desktop.
Save zats/7060237 to your computer and use it in GitHub Desktop.
Knowing the nature of text changes, helps to deal with it better.

Change type enumeration

typedef NS_ENUM(NSUInteger, SZSTextChangeType) {
	SZSTextChangeTypeDelete,
	SZSTextChangeTypeInsert,
	SZSTextChangeTypeReplace
};

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);
			break;
		}
		case SZSTextChangeTypeInsert: {
			NSString *stringToBeInserted = text;
			newSelectionRange = NSMakeRange(textView.selectedRange.location + [text length], 0);
			break;
		}
		case SZSTextChangeTypeInsert: {
			NSString *stringToBeReplaced = [textView.text substringWithRange:range];
			newSelectionRange = NSMakeRange(textView.selectedRange.location, textView.selectedRange.length + [text length]);
			break;
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment