Reputation: 63
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?
Upvotes: 6
Views: 5690
Reputation: 156
-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;
}
Upvotes: 6
Reputation:
When this function is called, currHeight.text still has length 0. The text only updates to 5 after you return YES.
The way to do what you want to do is test if currHeight.text.length is 0, string.length is 1 and the first character of string is numeric.
Upvotes: 1