2012-07-25 99 views
2

如何檢查UIKeyboardTypeDecimalPad是否有點/逗號?我需要這個來檢查輸入了多少點/逗號,所以我可以將它們限制爲1.我知道如何知道UIKeyboardTypeDecimalPad是否有逗號。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; 

} 
} 

是否有簡單的方法來檢查鍵盤是否有「,」或「。」?

回答

7

我懷疑該鍵上的字符是由當前語言環境治理。我說我懷疑是因爲我沒有測試過這個。如果這是正確的下面應該讓你決定是否一個逗號或句號/小數點有:

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

謝謝主席先生,這正是我一直在尋找! – maxus182 2012-07-26 12:34:36

相關問題