How can I allow backspace in a UITextField?
In my project, I have to limit the length of a UITextField
to 6 characters. This is working absolutely fine. Once I end editing and s开发者_StackOverflowtart editing again and I click backspace my application crashes.
Here is the code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [txtLicense.text length] + [strNumber length] - range.length;
return (newLength > 6) ? NO : YES;
}
Try this.
- (BOOL)textField:(UITextField *)inputTextField shouldChangeCharactersInRange (NSRange)range replacementString:(NSString *)string
{
return (textField.text.length >= 5 && range.length == 0) ? NO : YES;
}
Implement your delegate method as follows –
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range
withString:string];
return ([toBeString length] > 6) ? NO : YES;
}
We will get what the resultant string will be and check its length. This way backspaces would work.
If you want to achieve maximum length validation in UITextField you can use following working code from one of my working project.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text length] > 6) {
textField.text = [textField.text substringToIndex:6];
return NO;
}
return YES;
}
I am not sure what you want to achieve here, well you can try this one:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (string && [string length] && [textField.text length] <= 6) {
return NO;
}
return YES;
}
精彩评论