UIKeyboardTypeDecimalPad检测它是否有逗号“,”或点“。”

时间:2012-07-25 16:39:13

标签: iphone ios xcode uikeyboard

如何检查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;

}
}

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

1 个答案:

答案 0 :(得分:7)

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

NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];