gpt4 book ai didi

iphone - 在 UITextfield 中使用 NSNumberFormatter 进行实时格式化

转载 作者:太空狗 更新时间:2023-10-30 03:45:24 27 4
gpt4 key购买 nike

我有 UITextfield,用户可以在其中输入美元金额,我希望文本字段的格式始终为两位小数 ($ .##)。必须始终保持格式。但我仍然坚持如何将输入的数字附加到文本字段中的现有数字?

//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;
}

关于iphone - 在 UITextfield 中使用 NSNumberFormatter 进行实时格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2412491/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com