アプリケーションに、計算機のように機能させたい UITextField があります。デフォルト値の 0.00 が必要です。ユーザーが数字を入力すると、数字が右から左に移動し、一度に 0.00 のゼロが 1 桁ずつ置き換えられます。アプリケーションは、コンマ (,) を追加できるほどスマートでなければなりません。 3桁ごとに。これを行うために、デリゲート メソッドを実装しています。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {}
次のように:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]]
isEqualToString:@""])
return YES;
NSString *previousValue = [[[textField.text stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""];
string = [string stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSString *modifiedValue = [NSString stringWithFormat:@"%@%@",previousValue,string];
modifiedValue = [NSString stringWithFormat:@"%@.%@",[modifiedValue substringToIndex:modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];//this is the line that is causing the error
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
modifiedValue = [formatter stringFromNumber:[NSNumber numberWithFloat:[modifiedValue floatValue]]];
textField.text = modifiedValue;
return NO;
}
ただし、次のエラーが発生します。
'NSRangeException', reason: '*** -[__NSCFString substringToIndex:]: Range or index out of bounds'
このエラーは、テキスト フィールドに数値を入力しようとした瞬間にスローされました。誰かが私が間違っていることを見ることができますか?
回答者全員に事前に感謝します。