ユーザーの入力を既に変更している iOS アプリに UITextField があります。UITextField が一定数の文字を保持できることも確認する必要があることに気付きました。私は次のようにデリゲートメソッドを実装しています:
- (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];
if ([modifiedValue length] == 1) {
modifiedValue = [NSString stringWithFormat:@"0.0%@", string];
}
else if ([modifiedValue length] == 2) {
modifiedValue = [NSString stringWithFormat:@"0.%@%@", previousValue, string];
}
else if ([modifiedValue length] > 2) {
modifiedValue = [NSString stringWithFormat:@"%@.%@",[modifiedValue substringToIndex: modifiedValue.length-2],[modifiedValue substringFromIndex:modifiedValue.length-2]];
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:modifiedValue];
modifiedValue = [formatter stringFromNumber:decimal];
[textField setText:modifiedValue];
return NO;
}
上記のコードで、22 文字の制限を考慮に入れる方法がわかりません。誰が私が何をする必要があるかを見ることができますか?