Reputation: 252
I have implemented multiple UITextField's
and want to switch to the next text field if max limit is reached. I have implemented following delegate method but for some reason it is crashing and not switching to the next text field when limit is reached...
Any help would be greatly appreciated...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(@"%s", __FUNCTION__);
NSString *totalText = [textField.text stringByAppendingString:string];
NSLog(@"Length : %d", [totalText length]);
switch (textField.tag) {
case FirstTextFieldTag: {
if ([totalText length] > MaxLentgthTextField1) {
[self.textField1 resignFirstResponder];
[self.textField2 becomeFirstResponder];
}
break;
}
case SecondTextFieldTag: {
if ([totalText length] > MaxLentgthTextField2) {
[self.textField2 resignFirstResponder];
[self.textField3 becomeFirstResponder];
}
break;
}
case ThirdTextFieldTag: {
if ([totalText length] > MaxLentgthTextField3) {
[self.textField3 resignFirstResponder];
[self.textField4 becomeFirstResponder];
}
break;
}
case FourthTextFieldTag: {
if ([totalText length] > MaxLentgthTextField4) {
[self.textField4 resignFirstResponder];
[self.textField5 becomeFirstResponder];
}
break;
}
case FifthTextFieldTag: {
if ([totalText length] > MaxLentgthTextField5) {
[self.textField5 resignFirstResponder];
return NO;
}
break;
}
default:
break;
}
return YES;
}
Upvotes: 0
Views: 204
Reputation: 3399
The way you are finding the length of string seems inappropriate.
NSString *totalText = [textField.text stringByAppendingString:string];
NSLog(@"Length : %d", [totalText length]);
Instead, use this to find the length of string
NSUInteger newLength = [textField.text length] + [string length] - range.length;
Upvotes: 0
Reputation: 390
without having seen your crash log. this part is definitly wrong
NSString *totalText = [textField.text stringByAppendingString:string];
the new text of the textfield is not calculated by appending the changed characters but by changing the characters in the given range
Please try this and then tell us the result
NSString * totalText = [textField.text stringByReplacingCharactersInRange:range withString:string];
Upvotes: 1