To select a specific range of characters, you can do something similar 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 and other UIKit elements have their own subclasses UITextPosition and UITextRange , you cannot create new values ββdirectly, but you can use a text field to create them for you from a link to the beginning or end of the text and an integer offset.
You can also do the opposite to get whole 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 that adds methods for handling selections using NSRange s. https://gist.github.com/4463233
Anthony Mattox Jan 05 '13 at 19:00 2013-01-05 19:00
source share