Ale*_*ore 5 iphone cocoa-touch
我知道过去曾经问过几次,但我尝试的一切都失败了.我有一个带UILabel的自定义数字键盘.当我点击'1'时,UILabel显示一个.现在这就是我要做的事情:
现在键盘和UILabel工作得很好.我只需要让小数点现在正常工作.任何示例代码都很棒,(我应该把它放在我的应用程序中).如果您想查看我的代码,请告诉我.非常直截了当.感谢大家!
以下是我将如何做到的:
#define NUMBER_OF_DECIMAL_PLACES 2
NSMutableArray *typedNumbers = ...; //this should be an ivar
double displayedNumber = 0.0f; //this should also be an ivar
//when the user types a number...
int typedNumber = ...; //the number typed by the user
[typedNumbers addObject:[NSNumber numberWithInt:typedNumber]];
displayedNumber *= 10.0f;
displayedNumber += (typedNumber * 1e-NUMBER_OF_DECIMAL_PLACES);
//show "displayedNumber" in your label with an NSNumberFormatter
//when the user hits the delete button:
int numberToDelete = [[typedNumbers lastObject] intValue];
[typedNumbers removeLastObject];
displayedNumber -= (numberToDelete * 1e-NUMBER_OF_DECIMAL_PLACES);
displayedNumber /= 10.0f;
//show "displayedNumber" in your label with an NSNumberFormatter
Run Code Online (Sandbox Code Playgroud)
在浏览器中输入。警告实施者。使用NSDecimal而不是奖励积分double。
对发生的事情的解释:
我们本质上是在进行位移位,但是是以 10 为基数而不是以 2 为基数。当用户键入一个数字(例如:6)时,我们将现有数字向左移动一位小数(例如:0.000 => 00.00),然后乘以将键入的数字乘以 0.01 (6 => 0.06),并将其添加到现有数字 (00.00 => 00.06)。当用户输入另一个数字(例如:1)时,我们会执行相同的操作。左移 (00.06 => 00.60),将键入的数字乘以 0.01 (1 => 0.01),然后添加 (00.60 => 00.61)。存储号码的目的只是NSMutableArray为了方便删除。然而,这没有必要。只是一个方便而已。
当用户点击删除按钮(如果有)时,我们获取最后输入的数字(例如:1),将其乘以 0.01(1 => 0.01),然后从我们的数字中减去它(0.61 => 0.6),然后然后将我们的数字右移一位小数(0.6 => 0.06)。只要输入的数字数组中有数字,就重复此操作。当该数组为空时禁用删除按钮。
使用的建议NSDecimal只是允许非常高精度的数字。
| 归档时间: |
|
| 查看次数: |
414 次 |
| 最近记录: |