3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
syedfa
  • 2,801
  • 1
  • 41
  • 74

2 Answers2

3

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;
}
Community
  • 1
  • 1
ansible
  • 3,569
  • 2
  • 18
  • 29
0
     //Construct the new string with new input
     NSString* newText = [textField.text stringByReplacingCharactersInRange:range
                                                           withString:text];

     NSString *integerPart = [newText componentsSeparatedByString:@"."][0];
     NSString *decimalPart = [newText componentsSeparatedByString:@"."][1];

     if ([integerPart length] > 8 || [decimalPart length] > 5) {
         return NO;//this clause is always called.
     }

I believe this is what you need. This will construct the new string that will be displayed in the textfield and you can evaluate that string.

veovo
  • 191
  • 7