我想限制在 UITextField 中输入的数字。这是我的代码
#define MAX_NO_OF_DIGITS_BEFORE_DECIMAL 8
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
switch (textField.tag)
{
case BUY_ITEM_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.buyTextField.text];
}
}
break;
case BID_INCREMENT_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.bidTextField.text];
}
}
break;
case STARTING_BID_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.startingBidTextField.text];
}
}
break;
case SHIPPING_CHARGES_TEXTFILED:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.chargesTextField.text];
}
}
break;
default:
break;
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Check if we have 8 digits before decimal points
NSString *tempStr = [newString stringByReplacingOccurrencesOfString:CURRENCY_TYPE withString:@""];
if ([tempStr length]==MAX_NO_OF_DIGITS_BEFORE_DECIMAL)
{
// Check if we have only 1 decimal point
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
{
return NO;
}
else {
textField.text = [NSString stringWithFormat:@"%@%@%@",CURRENCY_TYPE,tempStr,@"."];
}
}
// Check if we have only 1 decimal point
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
{
return NO;
}
// Check if we have only 2 digits after decimal point
if([arrayOfString count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[arrayOfString objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
}
12345678.8
但我的问题是当我输入 12345678 时,它会将小数点放在 8 之后并再次放置 8 所以我的输出看起来像12345678.
我想要实现的是
1) 用户只能在小数点前输入 MAX_NO_OF_DIGITS_BEFORE_DECIMAL 和小数点后 2 位数字
我不明白为什么最后 8 会在此重复。有谁能够帮我 ?
提前致谢。