3rd December 2012

UITextField selectedRange

Guides | Tutorial By 4 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)];

Recommended Posts

Yammer integrations in ReactJS

Post by 4 years ago

I am writing this blog while I am working on a project for our client’s intranet website. The client requires the website has the ability to share, like and write comments in the website through

Got an idea?

We help entrepreneurs, organizations and established brands from around
the country bring ideas to life. We would love to hear from you!