簡単な ATM スタイルの通貨入力には、次のコードを使用します。これは、数字とバックスペースのみを許可するオプションを使用すると、非常にうまく機能します。UIKeyboardTypeNumberPad
NSNumberFormatter
最初に次のように設定します。
NSNumberFormatter* currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setMaximumSignificantDigits:9]; // max number of digits including ones after the decimal here
次に、次の shouldChangeCharactersInRange コードを使用します。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString* newText = [[[[textField.text stringByReplacingCharactersInRange:range withString:string] stringByReplacingOccurrencesOfString:currencyFormatter.currencySymbol withString:[NSString string]] stringByReplacingOccurrencesOfString:currencyFormatter.groupingSeparator withString:[NSString string]] stringByReplacingOccurrencesOfString:currencyFormatter.decimalSeparator withString:[NSString string]];
NSInteger newValue = [newText integerValue];
if ([newText length] == 0 || newValue == 0)
textField.text = nil;
else if ([newText length] > currencyFormatter.maximumSignificantDigits)
textField.text = textField.text;
else
textField.text = [currencyFormatter stringFromNumber:[NSNumber numberWithDouble:newValue / 100.0]];
return NO;
}
ほとんどの作業はnewText
値の設定で行われます。提案された変更が使用されますが、によって入力された数字以外の文字はすべて削除NSNumberFormatter
されます。
次に、最初の if テストで、テキストが空であるか、すべてゼロであるか (ユーザーまたはフォーマッターによって配置されたもの) を確認します。そうでない場合、次のテストで、数値がすでに最大桁数に達している場合、バックスペース以外の入力が受け入れられないことが確認されます。
最後の else は、フォーマッタを使用して数値を再表示するため、ユーザーには常に のようなものが表示されます$1,234.50
。このコードではプレースホルダー テキストにa を使用している$0.00
ため、テキストを nil に設定するとプレースホルダー テキストが表示されることに注意してください。