How can I limit the number of decimal points in a UITextField?

后端 未结 15 2294
说谎
说谎 2020-12-01 05:20

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal

15条回答
  •  爱一瞬间的悲伤
    2020-12-01 05:50

    Building on the accepted answer, the following approach validates three cases that are helpful when dealing with money formats:

    1. Extremely large amounts
    2. More than 2 characters after the decimal point
    3. More than 1 decimal points

    Make sure your text field's delegate is set properly, your class conforms to the UITextField protocol, and add the following delegate method.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
      // Check for deletion of the $ sign
      if (range.location == 0 && [textField.text hasPrefix:@"$"])
        return NO;
    
      NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
      NSArray *stringsArray = [updatedText componentsSeparatedByString:@"."];
    
      // Check for an absurdly large amount
      if (stringsArray.count > 0)
      {
        NSString *dollarAmount = stringsArray[0];
        if (dollarAmount.length > 6)
          return NO;
      }
    
      // Check for more than 2 chars after the decimal point
      if (stringsArray.count > 1)
      {
        NSString *centAmount = stringsArray[1];
        if (centAmount.length > 2)
          return NO;
      }
    
      // Check for a second decimal point
      if (stringsArray.count > 2)
        return NO;
    
      return YES;
    }
    

提交回复
热议问题