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
Just a small addition to the accepted answer. In iOS 5, the following line crashes my app when UITextView's text length is 0 (has no text):
[self textRangeFromPosition:startPosition toPosition:endPosition];
A small workaround is to add a length == 0 check like:
if (textField.text && textField.text.length > 0) {
// 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];
}