UITextField selectedRange

Guides | Tutorial By 5 years ago

Unfortunately getting and setting the text selection range for a UITextField instance is a bit trickier than on a UITextView. On the UITextView there is a simple selectedRange attribute for this purpose. For the UITextField, there is a solution but it’s a bit hidden away within the UITextInput protocol.

To make things easy, I’ve created this category for the UITextField which will implement the exact same behaviour as the UITextView.

@interface UITextField (Selection)

- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;

@implementation UITextField (Selection)

- (NSRange) selectedRange
	UITextPosition* beginning = self.beginningOfDocument;

	UITextRange* selectedRange = self.selectedTextRange;
	UITextPosition* selectionStart = selectedRange.start;
	UITextPosition* selectionEnd = selectedRange.end;

	const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
	const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];

	return NSMakeRange(location, length);

- (void) setSelectedRange:(NSRange) range
	UITextPosition* beginning = self.beginningOfDocument;

	UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
	UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
	UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];

	[self setSelectedTextRange:selectionRange];


And then you can use it like so:

[field becomeFirstResponder];
[field setSelectedRange:NSMakeRange(2, 5)];