这是很好的基础,但仍然不能满足我的应用需求。这是我做的帮助它。我知道代码实际上很麻烦,它在这里而不是提供线索,可能是为了获得更优雅的解决方案。
- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (aTextField == myAmountTextField) {
NSString *text = aTextField.text;
NSString *decimalSeperator = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
NSString *groupSeperator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
NSCharacterSet *characterSet = nil;
NSString *numberChars = @"0123456789";
if ([text rangeOfString:decimalSeperator].location != NSNotFound)
characterSet = [NSCharacterSet characterSetWithCharactersInString:numberChars];
else
characterSet = [NSCharacterSet characterSetWithCharactersInString:[numberChars stringByAppendingString:decimalSeperator]];
NSCharacterSet *invertedCharSet = [characterSet invertedSet];
NSString *trimmedString = [string stringByTrimmingCharactersInSet:invertedCharSet];
text = [text stringByReplacingCharactersInRange:range withString:trimmedString];
if ([string isEqualToString:decimalSeperator] == YES ||
[text rangeOfString:decimalSeperator].location == text.length - 1) {
[aTextField setText:text];
} else {
/* Remove group separator taken from locale */
text = [text stringByReplacingOccurrencesOfString:groupSeperator withString:@""];
/* Due to some reason, even if group separator is ".", number
formatter puts spaces instead. Lets handle this. This all should
be done before converting to NSNUmber as otherwise we will have
nil. */
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSNumber *number = [numberFormatter numberFromString:text];
if (number == nil) {
[textField setText:@""];
} else {
/* Here is what I call "evil miracles" is going on :)
Totally not elegant but I did not find another way. This
is all needed to support inputs like "0.01" and "1.00" */
NSString *tail = [NSString stringWithFormat:@"%@00", decimalSeperator];
if ([text rangeOfString:tail].location != NSNotFound) {
[numberFormatter setPositiveFormat:@"#,###,##0.00"];
} else {
tail = [NSString stringWithFormat:@"%@0", decimalSeperator];
if ([text rangeOfString:tail].location != NSNotFound) {
[numberFormatter setPositiveFormat:@"#,###,##0.0#"];
} else {
[numberFormatter setPositiveFormat:@"#,###,##0.##"];
}
}
text = [numberFormatter stringFromNumber:number];
[textField setText:text];
}
}
return NO;
}
return YES;
}
数字格式化程序以如下方式初始化:
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
numberFormatter.roundingMode = kCFNumberFormatterRoundFloor;
它是语言环境感知的,因此应该在不同的语言环境设置中正常工作。它还支持以下输入(示例):
0.00 0.01
1,333,333.03
请有人改进这一点。话题有点意思,目前还没有优雅的解决方案(iOS 没有 setFormat() 的东西)。