2011-04-04 4 views
1

以前は、shouldChangeCharactersInRangeイベントのテキストフィールドの長さを制限し、通貨フォーマットも適用しました。Obj-Cでは、ユーザーがUITextFieldに1以上を入力するようにするにはどうすればよいですか?

今回は、ユーザーが1以上を入力するようにする必要があります。

それは1、私はこれをどのように行うだろう

1000000経由にする必要がゼロとなるように、0001は受け入れられないだろうか? *「あなたが送る何であなたが受け入れる 何でリベラルと保守的である」:

は、これは私がこれまで

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

    BOOL res = TRUE; 

    NSString *newString = [textField.text stringByReplacingCharactersInRange: 
     range withString:string]; 
    newString = [NSString stringWithFormat:@"%d", [newString intValue]]; 
    res = !([newString length] > 8); 

    return res; 
} 
+2

あなたは 'NSNumberFormatter'を全く見ていませんか? – Richard

答えて

2

UIのための良いルールが持っているものです。

あなたのアプリが好きなフォーマットに合わない入力のためにユーザーを罰するのではなく、適切なフォーマットに変換できるものを受け入れます。 1万から100万の整数を必要とする場合、0001は奇妙ではありますが完全に有効な入力です。私は、このソリューションを提案:

// Only check the value when the user is _done_ editing. 
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 

    NSInteger intVal = [textField.text integerValue]; 
    // Check whether the input, whatever it is, 
    // can be changed into an acceptable value 
    if((intVal <= 1000000) && (intVal >= 1)){ 
     // If so, display the format we want so the 
     // user learns for next time 
     textField.text = [[NSNumber numberWithInteger:intVal] stringValue]; 
     return YES; 
    } 

    // Else show a small error message describing 
    // the problem and how to remedy it 
    return NO; 
} 

*:もともと"Robustness Principle"としてジョン・ポステルによって策定します。よりUI固有のステートメントがあるかもしれませんが、私は現時点では思い出すことができません。

+0

実際には、 'stringWithFormat:' - 'textField.text = [NSString stringWithFormat:@"%ld "、intVal];'を使用すると、おそらく私が言っていることと一直線になるでしょう。必要なものがあれば、入力フォーマットを正確に修正してください。もちろん、NSNumberFormatterもこの種のために設計されています。 –

関連する問題