Search code examples
iphoneiosuitextfielduitextfielddelegate

UITextField - Add a character/s after 1st character is entered while typing


I have a UITextField which will contain height value. I want to format the value of the field while the user is typing into the UITextField. e.g. if I want to enter the value as "5 ft 10", the flow will be:

1. Enter 5
2. " ft " is appended immediately after I type 5 with leading & trailing space.

My code looks like this:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range       replacementString:(NSString *)string
{   

if ( [string isEqualToString:@""] ) return YES;

// currHeight Formatting
if ( textField == currHeight )  { 
   if (currHeight.text.length == 1) {   
        currHeight.text = [NSString stringWithFormat:@"%@ ft ", currHeight.text];    
        }
}
return YES; 
}

I am stuck at the point where I enter 5 nothing happens. I have to tap any button for the " ft " to be appended.

Can I do this without tapping anything?


Solution

  • -shouldChangeCharactersInRange gets called before the change to the text field takes place, so the length is still 0 (see Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?). Try this instead:

    - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
    replacementString: (NSString*) string {
        if (textField == currHeight) {
            NSString *text = [textField.text stringByReplacingCharactersInRange:range
            withString: string];
            if (text.length == 1) { //or probably better, check if int
                textField.text = [NSString stringWithFormat: @"%@ ft ", text];
                return NO;
            }
        }
        return YES;
    }