2

如何检查 UIKeyboardTypeDecimalPad 是否有点/逗号?我需要这个来检查输入了多少个点/逗号,这样我就可以将它们限制为只有 1 个。当我知道 UIKeyboardTypeDecimalPad 有逗号时,我知道该怎么做。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSCharacterSet *cs;
NSString *filtered;

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

if ([textField.text rangeOfString:@","].location == NSNotFound) {

    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet];
    filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
 }


else {

    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];     

    NSUInteger count = 0, length = [newString length];
    NSRange range = NSMakeRange(0, length); 
    while(range.location != NSNotFound)
    {
        range = [newString rangeOfString: @"," options:0 range:range];
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            count++; 
        }
    }        

    if (count < 2) {

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

        return YES;

    }

    return NO;

}
}

有没有简单的方法来检查键盘是否有“,”或“。”?

4

1 回答 1

7

我怀疑该键上的字符受当前语言环境的约束。我说我怀疑是因为我没有测试过这个。如果这是正确的,则以下内容应允许您确定是否存在逗号或句点/小数点:

NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
于 2012-07-25T19:55:14.627 回答