2013-02-19 70 views
2

我正在開發一個iOS應用程序,要求用戶輸入美元金額。它需要允許他們進入美元和美分的$ 9999.99實時格式化美元金額

一個最大值,我希望它是這樣工作的: 有一個顯示文本框:「$ 0.00」 輸入$ 5.25的輸入將與每個鍵更改按。 所以它看起來像這樣:按下$ 0.05 '2',顯示:按$ 0.52 '5',顯示:按 '5',顯示$ 5.25

我試圖讓這個工作不同方式的數量,但都存在這個問題。 使用NSNumberformatter無法正常工作。如果用戶按下退格鍵,使用鏈接列表或數組將不會工作,我真的不想實現一個堆棧,因爲我擔心這太費時。請告訴我應該如何處理這個問題。謝謝

+0

我想你只格式化字符串蠻力並顯示,每次按下按鈕後更新。 – 2013-02-19 20:07:54

+0

你能解釋一下嗎? – 2013-02-19 20:10:12

+4

NSNumberFormatter可以正常工作(這在很多應用程序中都是常見的)。也許發佈你試圖使用它,並且有人可以指出錯誤。 – 2013-02-19 20:10:55

回答

1

這只是一個指示性的例子,顯示如何做到這一點。你應該研究這些代碼,並將其重新適應你的情況。試試看:

@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= @","; 
    [email protected]""; 

    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)]); 
    } 
} 
+0

丹納並沒有試圖以美元和美分格式化數字。他想要一個UITextField,它將在用戶鍵入和刪除字符時動態格式化。 – 2013-02-19 20:55:52

+0

足以將此代碼重新應用到從文本字段輸入的字符串中。 – 2013-02-19 21:11:49

0
NSString* formattedAmount = [NSString stringWithFormat:@"$%01d.%02d",dollars,cents];