iphone – 如何验证文本字段中只允许单个小数点的文本字段?

我需要限制用户只在小数点后输入两位数.我通过在textfield delegate shouldChangeCharactersInRange中执行以下代码来实现此目的.但它允许输入多个点.如何限制这个?提前致谢.

            NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSArray *sep = [newString componentsSeparatedByString:@"."];
            if([sep count]>=2)
            {
                NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
                NSLog(@"sepStr:%@",sepStr);

                return !([sepStr length]>2);
            }
            return YES;
最佳答案
 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

NSString *sepStr;

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count]>=2)
   {
        sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        NSLog(@"sepStr:%@",sepStr);
        if([sepStr length] >2)
       {
        return NO;
       }
    else 
       {
        return YES;
       }

   }
   return YES;
 }

转载注明原文:iphone – 如何验证文本字段中只允许单个小数点的文本字段? - 代码日志