2011-08-05 104 views
0

在文本字段中,我應該寫一個數字:該數字可以是點(10.23)或無點(10);但我應該檢查這個數字是一個數字而不是一個字。我可以檢查在文本框中是否有一個數字,而不是一個單詞? 例如:如果我寫了一個單詞而不是一個數字,我希望有一個nslog表明存在錯誤。IOS:檢查文本字段文本

回答

3

另一種方式:

NSString *string = @"684.14"; 
NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet]; 
BOOL stringIsValid = ([[string stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@""] || 
         [[string stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@"."]); 

還記得你可以使用textField.keyboardType = UIKeyboardTypeNumberPad;的鍵盤。 (這不會保證只有數字輸入,但是,這只是關於用戶友好性。)

0

退房NSScannerhttps://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003726

if([[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL]) 
    NSLog(@"\"-123.4e5\" is numeric"); 
else 
    NSLog(@"\"-123.4e5\" is not numeric"); 
if([[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL]) 
    NSLog(@"\"Not a number\" is numeric"); 
else 
    NSLog(@"\"Not a number\" is not numeric"); 
// prints: "-123.4e5" is numeric 
// prints: "Not a number" is not numeric