And*_*ant 51 iphone cocoa-touch
在我的应用中,用户需要能够输入带小数位的数值.iPhone没有提供专门用于此目的的键盘 - 只有数字键盘和带数字和符号的键盘.
是否有一种简单的方法来使用后者并防止输入任何非数字输入而无需正则表达式最终结果?
谢谢!
Zeb*_*ebs 53
我想最好指出,从iOS 4.1开始,你可以使用新的UIKeyboardTypeDecimalPad
.
所以现在你必须:
myTextField.keyboardType=UIKeyboardTypeDecimalPad;
Run Code Online (Sandbox Code Playgroud)
she*_*hek 49
更优雅的解决方案恰好也是最简单的.
您不需要小数分隔符键
为什么?因为您可以简单地从用户的输入中推断它.例如,在您输入1.23美元的美国语言环境中,首先输入数字1-2-3(按此顺序).在系统中,当输入每个字符时,这将被识别为:
请注意我们如何根据用户的输入推断出小数分隔符.现在,如果用户想要输入$ 1.00,他们只需输入数字1-0-0.
为了使您的代码能够处理不同语言环境的货币,您需要获取货币的最大小数位数.这可以使用以下代码段完成:
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
int currencyScale = [currencyFormatter maximumFractionDigits];
Run Code Online (Sandbox Code Playgroud)
例如,日元的最大分数为0.因此,在处理日元输入时,没有小数分隔符,因此无需担心分数.
这种解决问题的方法允许您使用Apple提供的库存数字输入键盘,而不会出现自定义键盘,正则表达式验证等问题.
Mik*_*ler 12
以下是已接受答案中建议的解决方案示例.这不处理其他货币或任何东西 - 在我的情况下,我只需要支持美元,无论当地/货币是什么,所以这对我来说还可以:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
double currentValue = [textField.text doubleValue];
//Replace line above with this
//double currentValue = [[textField text] substringFromIndex:1] 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);
}
textField.text = [NSString stringWithFormat:@"%.2f", cents / 100.0f];
//Add this line
//[textField setText:[NSString stringWithFormat:@"$%@",[textField text]]];
return NO;
}
Run Code Online (Sandbox Code Playgroud)
轮和层是重要的a)因为浮点表示有时会丢失.00001或其他什么,以及b)格式字符串舍入我们在退格部分中删除的任何精度.
归档时间: |
|
查看次数: |
30819 次 |
最近记录: |