現在、ユーザーが通貨値 (小数点はオプション) を UITextField に入力する必要があるアプリを作成しています。私の問題は、特定の小数点の後に 2 つ以上の数字を防止すると同時に、複数の小数点を防止しようとすると発生します。私はウェブ上で調査しましたが、正確な答えを見つけることができませんでした。おそらく shouldChangeCharactersInRange を使用する必要があることがわかりましたが、正確な使用方法がわかりません...
ありがとう、ヴィリンド・ボラ
現在、ユーザーが通貨値 (小数点はオプション) を UITextField に入力する必要があるアプリを作成しています。私の問題は、特定の小数点の後に 2 つ以上の数字を防止すると同時に、複数の小数点を防止しようとすると発生します。私はウェブ上で調査しましたが、正確な答えを見つけることができませんでした。おそらく shouldChangeCharactersInRange を使用する必要があることがわかりましたが、正確な使用方法がわかりません...
ありがとう、ヴィリンド・ボラ
数値フォーマッタを使用します。
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:@"###0.##"];
NSString *formattedNumberString = [numberFormatter stringFromNumber:@122344.4563];
NSLog(@"formattedNumberString: %@", formattedNumberString);
// Output for locale en_US: "formattedNumberString: formattedNumberString: 122,344.45"
これを のような UITextFieldDelegate メソッドの 1 つに配置しますtextField:shouldChangeCharactersInRange:replacementString:
。次のようにして最新の文字列NSString *s = [textField.text stringByReplacingCharactersInRange:range withString:string];
を取得します。次に、その文字列の数値を で取得し、@([s floatValue])
上記のような数値フォーマッタを使用して、テキスト フィールドに入力します。
入力をいじる前に、小数点の後に少なくとも2桁入力したことを確認するためにいくつかのチェックを行います。しかし、これは正しいローカライズされた方法です。
// add a notification & use following function:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textIsChanged:) name:UITextFieldTextDidChangeNotification object:nil];
-(void)textIsChanged:(NSNotification*)notification
{
NSString * currentText = yourTextField.text;
if ([currentText rangeOfString:@"."].location != NSNotFound)
{
NSArray *arr = [currentText componentsSeparatedByString:@"."];
if(arr.count == 2)
{
NSString *afterDecimalPart = [arr objectAtIndex:1];
if(afterDecimalPart.length > 2)
{
currentText = [currentText substringToIndex:currentText.length-1];
yourTextField.text = currentText;
}
}
}
}