I have a UITextField in my iPhone app. I know how to make the text field select all of its text, but how can change the selection? Say I wanted to select the last 5 characte
To select a specific range of characters you can do something like this in iOS 5+
int start = 2;
int end = 5;
UITextPosition *startPosition = [self positionFromPosition:self.beginningOfDocument offset:start];
UITextPosition *endPosition = [self positionFromPosition:self.beginningOfDocument offset:end];
UITextRange *selection = [self textRangeFromPosition:startPosition toPosition:endPosition];
self.selectedTextRange = selection;
Since UITextField
s and other UIKit elements have their own private subclasses of UITextPosition
and UITextRange
you can not create new values directly, but you can use the text field to create them for you from a reference to the beginning or end of the text and an integer offset.
You can also do the reverse to get integer representations of the start and end points of the current selection:
int start = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start];
int end = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.end];
Here is a category which adds methods to handle selections using NSRange
s. https://gist.github.com/4463233