[英]Realtime formatting with NSNumberFormatter in a UITextfield
我有UITextfield,用户可以输入一个美元金额,我希望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];
}
这是个主意......
存储字符串值,附加到它,然后将其用于操作。
在.h文件中定义NSMutableString
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.