在UITextfield中使用NSNumberFormatter实时格式化 [英] Realtime formatting with NSNumberFormatter in a UITextfield
本文介绍了在UITextfield中使用NSNumberFormatter实时格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有UITextfield,用户可以放入一个美元的金额,我想文本字段总是格式化两个小数($。##)。格式化必须始终保持。但我坚持如何附加输入的数字到文本字段中的现有的数字?
I have UITextfield where a user can put in a dollar amount, I would like the textfield always to be formatted with two decimals ($ .##). The formatting has to be maintained all the time. But i'm stuck on how to append the entered numbers to existing ones in the textfield ?
//This delegate is called everytime a character is inserted in an UITextfield.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField tag] == amountTag)
{
NSString *amount = string;
//How do I append the already entered numbers in the textfield to the new entered values ?
//??
//Get new formatted value
NSString *newAmount = [self formatCurrencyValue:[amount doubleValue]];
[textField setText:[NSString stringWithFormat:@"%@",newAmount]];
return NO;
}
//Returning yes allows the entered chars to be processed
return YES;
}
-(NSString*) formatCurrencyValue:(double)value
{
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init]autorelease];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}
推荐答案
存储字符串值,附加到它,然后用于操作。
Store the string value, append to it, then use that for the operation.
定义NSMutableString .h文件
Define an NSMutableString in the .h file
NSMutableString *storedValue;
@property (nonatomic, retain) NSMutableString *storedValue;
合成。
...
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField tag] == amountTag)
{
[storedValue appendString:string];
NSString *newAmount = [self formatCurrencyValue:([storedValue doubleValue]/100)];
[textField setText:[NSString stringWithFormat:@"%@",newAmount]];
return NO;
}
//Returning yes allows the entered chars to be processed
return YES;
}
这篇关于在UITextfield中使用NSNumberFormatter实时格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文