我找到了下面的代碼,我試圖在UITableView的shouldChangeCharactersInRange事件中工作。沒有貨幣符號,它工作正常。iPhone:如何在shouldChangeCharactersInRange中添加貨幣符號,小數點和小數位
當我嘗試添加貨幣符號時,它只是允許我輸入一個數字。它應該做的是這樣的,比如說我輸入7536,它應該出現在以下步驟中:£0.07,£0.75,£7.53,£75.36,而不是0.07,£0.05,£0.03,£0.06
繼承人的代碼。
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{ BOOL res = TRUE;
double currentValue = [textField.text doubleValue];
double cents = round(currentValue * 100.0f);
if ([string length]) {
for (size_t i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (isnumber(c)) {
cents *= 10;
cents += c - '0';
}
}
} else {
// back Space
cents = floor(cents/10);
}
// This line next works without the currency symbol
//textField.text = [NSString stringWithFormat:@"%.2f", cents/100.0f];
NSMutableString *aString = [NSMutableString stringWithFormat:@"%@", strCurrencySymbol];
[aString appendFormat:@"%.2f", cents/100.0f];
textField.text = aString;
res = NO;
return res;
}
我不知道我明白你可以給我完整的shouldChangeCharactersInRange函數。我不打算啓用自動完成。另外,我懷疑$ 100.00會經常進入。我將通過不同的貨幣符號和小數位。 – Jules 2010-09-26 19:32:12
在調用'-doubleValue'獲得'currentValue'之前,您需要去掉貨幣符號。我的代碼這樣做。其餘的代碼可以遵循。 – 2010-09-26 22:07:34
開始時的值不會有貨幣符號,整個問題是我想添加它並在每次按鍵後顯示它。對不起,如果不明確。 – Jules 2010-09-27 10:52:26