Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 实时格式化美元金额_Iphone_Ios_Objective C_Mobile - Fatal编程技术网

Iphone 实时格式化美元金额

Iphone 实时格式化美元金额,iphone,ios,objective-c,mobile,Iphone,Ios,Objective C,Mobile,我正在开发一个iOS应用程序,要求用户输入美元金额。它需要允许他们输入最大值为$9999.99的美元和美分 我希望它能像这样工作: 有一个文本字段显示:“$0.00” 要键入$5.25,输入将随每次按键而改变。 所以看起来是这样的: 按下“5”,显示:$0.05 按下“2”,显示:$0.52 按下“5”,显示:$5.25 我尝试了很多不同的方法来实现这一点,但都存在问题。 使用NSNumberformatter无法正常工作。如果用户按backspace键,使用链接列表或数组将不起作用,我真的不想

我正在开发一个iOS应用程序,要求用户输入美元金额。它需要允许他们输入最大值为$9999.99的美元和美分

我希望它能像这样工作: 有一个文本字段显示:“$0.00” 要键入$5.25,输入将随每次按键而改变。 所以看起来是这样的: 按下“5”,显示:$0.05 按下“2”,显示:$0.52 按下“5”,显示:$5.25

我尝试了很多不同的方法来实现这一点,但都存在问题。
使用NSNumberformatter无法正常工作。如果用户按backspace键,使用链接列表或数组将不起作用,我真的不想实现堆栈,因为我担心这会太耗时。请告诉我该如何处理这个问题。谢谢

这只是一个说明如何操作的指示性示例。您应该研究此代码,并根据自己的情况重新调整它。试试看:

@autoreleasepool
{
    // Here I create the formatter and I set the format. You do this faster with setFormat: .
    NSNumberFormatter* formatter=[[NSNumberFormatter alloc]init];
    formatter.numberStyle= NSNumberFormatterCurrencyStyle;
    formatter.maximumIntegerDigits=6;
    formatter.maximumFractionDigits=2;
    formatter.currencySymbol= @"$";
    formatter.currencyDecimalSeparator= @".";
    formatter.currencyGroupingSeparator= @",";
    formatter.positivePrefix=@"";

    NSArray* numbers= @[ @1 ,@2 ,@3 ,@4, @5, @6, @7, @8  ];
    // These are the inserted numbers, you should change the code in a way that
    // every number is taken in input from the text field.
    float number=0.0f;
    for(NSUInteger i=0;i<8;i++)
    {
        // It just simulates what happens if the user types the numbers in the array.
        number= [numbers[i] floatValue] * 1.0e-2 + number*10;
        NSLog(@"%@",[formatter stringFromNumber: @(number)]);
    }
}
@autoreleasepool
{
//在这里,我创建了格式化程序并设置了格式。使用setFormat可以更快地完成此操作:。
NSNumberFormatter*格式化程序=[[NSNumberFormatter alloc]init];
formatter.numberStyle=NSNumberFormatterCurrencyStyle;
formatter.maximumIntegerDigits=6;
formatter.maximumFractionDigits=2;
formatter.currencySymbol=@“$”;
formatter.currencyDecimalSeparator=@“;
currencyGroupingSeparator=@“,”;
formatter.positivePrefix=@;
NSArray*数字=@[@1,2,3,4,5,6,7,8];
//这些是插入的数字,您应该以以下方式更改代码:
//每个数字都从文本字段输入。
浮点数=0.0f;

对于(i=0;我认为您应该格式化字符串暴力并显示它,在每次按下按钮后进行更新。您能进一步解释一下吗?NSNumberFormatter对此很有用(这在许多应用程序中很常见)。也许发布您尝试如何使用它,有人可以指出错误。这有帮助吗?Tanner并不是试图用美元和美分格式化数字。他想要一个UITextField,它将随着用户键入和删除字符而动态格式化。足以将此代码重新调整为从文本字段输入的字符串。
NSString* formattedAmount = [NSString stringWithFormat:@"$%01d.%02d",dollars,cents];