Question

I'm creating a text field that allows the user to enter a date, and I want to show the format required: mm-dd-yyyy. As they type, it should replace the format with the numbers they type. For instance, if they enter 125, it should look like: 12-5d-yyyy.

I've been able to get this working (using the textField:shouldChangeCharactersInRange:replacementString: method). But there are 2 problems:

  1. When I update the text field so that it shows the format plus what they have typed (by directly setting textField.text) the cursor goes to the end of the inserted text. For example, it currently looks like: 12-30-yyyy| (where | is the cursor), but I want it to look like 12-30-|yyyy. So how can I place the cursor where they last typed?

  2. I have not been able to determine where a deletion occurs if the user presses backspace or delete. The only way I know to determine that they pressed backspace or delete is like this: BOOL thisIsBackspace = ([string length] == 0) (where string is the value of replacementString:. But this doesn't tell me where it occurred. So how can I determine where a deletion occurs in UITextField?

Was it helpful?

Solution

Using the UIDatePicker would be the way to go. Aside from that...

In textField:shouldChangeCharactersInRange: the range parameter will tell you where where in the field the actual change is occurring.

You can also use stringByReplacingCharactersInRange to create the value of the field after edit. Then you can use it to compare and find where they edited.

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Now you can compare text and textField.text and find where they are different.

    return YES;
}

OTHER TIPS

You can place the cursor by using:

[textField setSelectedRange:NSMakeRange(desiredPosition, 0)];

You can determine where the deletion was made by using the "range" input for the method

textField:shouldChangeCharactersInRange:replacementString:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top