I am implementing the following delegate method for UITextField:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *integerPart = [textField.text componentsSeparatedByString:@"."][0];
NSString *decimalPart = [textField.text componentsSeparatedByString:@"."][1];
if ([integerPart length] > 8 || [decimalPart length] > 5) {
return NO;//this clause is always called.
}
...
}
I am trying to limit the number of digits entered in the textField to 6. The problem I have is that if I enter a number with 6 digits after the decimal, and then try to press the backspace key on my device to delete the numbers, or need to make a correction inside the number, I'm unable to.
The reason is that whenever it comes to this point in my code, it notices that I have already entered 6 digits after the decimal (which is correct), and thus, nullifies my backspace key entry. How do I maintain this limit of 6 digits after the decimal place, AND allow for editing of the number after reaching this limit?
I haven't had a chance to test this, but according to this answer, string should be empty when a backspace is entered (which makes sense). So you should be able to do this.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Always allow a backspace
if ([string isEqualToString:@""]) {
return YES;
}
// Otherwise check lengths
NSString *integerPart = [textField.text componentsSeparatedByString:@"."][0];
NSString *decimalPart = [textField.text componentsSeparatedByString:@"."][1];
if ([integerPart length] > 8 || [decimalPart length] > 5) {
return NO;//this clause is always called.
}
return YES;
}