Can I select a specific block of text in a UITextField?

To select the name of a file without the file extension, use this:

-(void) tableViewCellDidBeginEditing:(UITableViewTextFieldCell*) cell
{
    NSInteger fileNameLengthWithoutExt = [self.filename length] - [[self.filename pathExtension] length];
    UITextField* textField = cell.textField;
    UITextPosition* start = [textField beginningOfDocument];
    UITextPosition* end = [textField positionFromPosition:start offset: fileNameLengthWithoutExt - 1]; // the -1 is for the dot separting file name and extension
    UITextRange* range = [textField textRangeFromPosition:start toPosition:end];
    [textField setSelectedTextRange:range];
}

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 UITextFields 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 NSRanges. https://gist.github.com/4463233


With UITextField, you cannot. But if you see the headers, you have _selectedRange and others that might be used if you add some categories to it ;)


Update for iOS5 and above :

Now UITextField and UITextView conform to UITextInput protocol so it is possible :)

Selecting the last 5 characters before the caret would be like this:

// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];

// Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:-5];

// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start];

// Set new range
[textField setSelectedTextRange:newRange];