ios – How do I set the cursor position of a UITextField when it was tapped?


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

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img