Text Selection in UITextField

Selecting a part of an entered Text in a UITextField is not as easy as it seems. You need to do several steps to get to the goal.

The word entered in the textField is: PHILADELPHIA

itemAEntry1 is the textField in which the selection should take place.

int startpointIndex = 2; //the starting point Index is 2 (meaning the selection starts at the 3rd letter, remember the index starts with 0, first letter in the UITextField is 0)

int lengthOfSelection = 5; //requested length is 5 (5 characters will be selected)        

NSRange toBeSelectedRange = NSMakeRange(startpointIndex, lengthOfSelection); //this creates the Range for the later selection

[itemAEntry1 becomeFirstResponder]; //first the text field needs to become first responder

UITextPosition *zeroIndexOfTextfield = itemAEntry1.beginningOfDocument; //here we find the start of the text field

UITextPosition *startOfSelection = [itemAEntry1 positionFromPosition:zeroIndexOfTextfield offset:toBeSelectedRange.location]; //here we generate the starting point of the selection by offsetting the location of the Chosen Range

UITextPosition *endOfSelection = [itemAEntry1 positionFromPosition:startOfSelection offset:toBeSelectedRange.length]; //here we find the end point of the selection by offsetting the length of the Chosen Range

UITextRange *createdRange = [itemAEntry1 textRangeFromPosition:startOfSelection toPosition:endOfSelection]; //here we generate the text Range by using the found starting and ending Position

[itemAEntry1 setSelectedTextRange:createdRange]; //select the above created Range in the Text field 

This code results in selecting the Part "ILADE" in the word PHILADELPHIA.

© MR-Apps 2011-2013