我的应用程序中有一个 UITextField,我想像计算器一样工作。我需要它具有默认值 0.00,并且当用户输入数字时,数字从右向左移动,一次替换 0.00 中的零,并且应用程序应该足够聪明,可以添加逗号 (,)每三位数字之后。为此,我正在实现委托方法:
- (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'
当我尝试在文本字段中输入数字时引发此错误。谁能看到我做错了什么?
提前感谢所有回复的人。