I want to force set the cursor position when I tap a UITextField. For example, before tapping, the text is “100.00%”, after tapping, it should display as “100.00|%”.
I’d try changing textField.selectedTextRange at textFieldDidBeginEditing:, but it didn’t work.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
NSInteger cursorPosition = textField.text.length - 1;
UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorPosition];
textField.selectedTextRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
}
The textField.selectedTextRange seems to be reset by UIKit after textFieldDidBeginEditing:, so I’d try changing textField.selectedTextRange at next run loop.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
dispatch_async(dispatch_get_main_queue(), ^{
NSInteger cursorPosition = textField.text.length - 1;
UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorPosition];
textField.selectedTextRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
});
}
It works, but it’s not so good, because the cursorView blinked from the last 1st position of the text into last 2nd position of the text.
Appreciated for telling me how was that, and how to implement




