在实现委托方法时获取IndexOutofBoundsException应在iOS中更改CharactersRange
我的应用程序中有一个UITextField,我希望它像计算器一样工作。我需要它的默认值为0.00,当用户输入数字时,数字从右向左移动,每次替换0.00中的零一个数字,并且应用程序应该足够智能,可以在每三个数字后添加逗号(,)。为此,我正在实现委托方法:在实现委托方法时获取IndexOutofBoundsException应在iOS中更改CharactersRange,ios,uitextfield,uitextfielddelegate,Ios,Uitextfield,Uitextfielddelegate,我的应用程序中有一个UITextField,我希望它像计算器一样工作。我需要它的默认值为0.00,当用户输入数字时,数字从右向左移动,每次替换0.00中的零一个数字,并且应用程序应该足够智能,可以在每三个数字后添加逗号(,)。为此,我正在实现委托方法: - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)strin
- (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'
这个错误是在我试图在文本字段中输入数字时抛出的。有人能看出我做错了什么吗
提前感谢所有回复者。是的,这里有一点:
[modifiedValue substringToIndex:modifiedValue.length-2]
似乎假定字符串的长度至少为2
这可能不是,至少当用户在空文本字段中键入他/她的第一个字符时是这样
如果长度大于两个字符,则只执行“shouldChangeCharactersInRange
”方法的核心部分,对整个过程进行长度检查,怎么样