我的 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 个字符的限制。谁能看到我需要做什么?