[英]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.