简体   繁体   中英

How can I determine the location of a deletion in an UITextField

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 .

  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.

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;
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM