将文本字段条目限制为仅一个小数点

时间:2011-11-10 07:26:50

标签: objective-c uitextfield decimal-point

我创建了一个文本字段来输入金额。我希望用户只能输入一个小数点。我在-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string方法中实现了它。

在一般情况下,它工作正常,但是如果按下退格键并删除单个小数点,之后它仍然假定已输入小数点,因此不再接受小数点。

每当按下退格键删除小数点时,我需要重置decimalPointEntered标志。怎么做?

10 个答案:

答案 0 :(得分:10)

这对我来说很好。试试这段代码:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSArray *sep = [newString componentsSeparatedByString:@"."];
    if([sep count] >= 2)
    { 
        NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        return !([sepStr length]>1);
    }
    return YES;
}

答案 1 :(得分:8)

以下是我使用的内容:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (!numberFormatter) {
        numberFormatter = [[NSNumberFormatter alloc]init];
        //[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    }
    NSNumber *test = [numberFormatter numberFromString:[self.text stringByAppendingString: string]];  // in case we entered two decimals

    return (test != nil);

}

答案 2 :(得分:3)

我有一个非常相似的解决方案。为我工作得更好。它还验证文本输入。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"in shouldChangeCharactersInRange");


    if([string length]==0){
        return YES;
    }

    //Validate Character Entry
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789,."];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];

        if ([myCharSet characterIsMember:c]) {

            //now check if string already has 1 decimal mark
            NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
            NSArray *sep = [newString componentsSeparatedByString:@"."];
            NSLog(@"sep: %@ count: %d" ,sep,[sep count]);
            if([sep count]>2) return NO;
            return YES;

        }

    }

    return NO;
}

答案 3 :(得分:3)

我限制我的用户输入金额应该是这样的

  • 用户应该只能输入0-9和十进制。字符
  • 只有一位小数。允许的字符
  • 十进制前最多5位数。
  • 小数点后最多2位数。
  

<强> 40543.48

所以我用这种方式更新了 shouldChangeCharactersInRange 方法

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   {

    if (textField == self.txtFieldTransferAmount)
    {
        NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSArray *stringsArray = [updatedText componentsSeparatedByString:@"."];

        // Before decimal only 5 digit allowed
        if (stringsArray.count > 0)
        {
            NSString *dollarAmount = stringsArray[0];
            if (dollarAmount.length > 5)
                return NO;
        }

        // After decimal only 2 digit allowed
        if (stringsArray.count > 1)
        {
            NSString *centAmount = stringsArray[1];
            if (centAmount.length > 2)
                return NO;
        }

        // Only one . decimal allowed
        if (stringsArray.count > 2)
            return NO;

        if (textField.text.length < 8) {
            //User should able to enter only 0-9 and . characters
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            return [string isEqualToString:filtered];
        }
        else
        {
            if (range.length > 0)
            {
                return true;
            }
            else{
                return false;
            }
        }
    }
    return true;
}

答案 4 :(得分:2)

愿这对某人有所帮助..

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        // if . at the beggining
        if ([newString isEqualToString:@"."] && newString.length== 1) {
            textField.text = @"0.";
            return NO;
        }

        // do not allow . more then once
        NSArray *components = [newString componentsSeparatedByString:@"."];
        if([components count] > 2)
        {
            return NO;
        }

答案 5 :(得分:1)

听起来你需要NSNumberFormatter

答案 6 :(得分:1)

尝试这是一个快速的代码,但你可以参考逻辑: -

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {


    if(string == "." ){
        let countdots = textField.text!.componentsSeparatedByString(".").count - 1

        if countdots > 0 && string == "."
        {
            return false
        }
    }
    return true 
}

答案 7 :(得分:0)

这是最简单的方法。


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSArray *explodedNumbersArray = [newString componentsSeparatedByString:@"."];

    // We check if the array has 3 or more items which means that it has 2 decimal places or more
    // we return NO if that happens so that the textfield will not recognize input
    if([explodedNumbersArray count] >= 3) {
        return NO;
    }

    return YES;
}

注意:确保应接收委托通知的视图或视图控制器应符合UITextFieldDelegate。

答案 8 :(得分:0)

我使用此方法将十进制字符数限制为一,并允许用户在需要时输入负数(即折扣):

NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890.-"] invertedSet];
if ([string rangeOfCharacterFromSet:cs].location == NSNotFound) {

    NSString *newString = [[textField text] stringByReplacingCharactersInRange:range withString:string];

    // check number of decimal chars used (maximum of one)
    NSArray *array = [newString componentsSeparatedByString:@"."];
    if ([array count] <= 2) {

        // check negative chars (maximum of one AND it must be at the front)
        array = [newString componentsSeparatedByString:@"-"];

        if (1 == [array count]) {
            return YES; // no negatives
        } else if (2 == [array count]) {
            return ('-' == [newString characterAtIndex:0]); // return YES if first char is negative only
        } else {
            return NO; // too many negative chars
        }
    } else {
        return NO; // too many decimal chars
    }
} else {
    return NO; // invalid character
}

答案 9 :(得分:0)

在这种情况下,我总是更喜欢使用正则表达式而不是基于代码的规则。

要限制小数点后一位,请在下面使用;

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   // Only allow one decimal point and 1 digit after it
   NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
   NSString *expression = @"^[0-9]$*((\\.|,)[0-9]{0,1})?$";
   NSError *error = nil;
   NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
   NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
   return numberOfMatches != 0;
   return YES;
 }

上面的代码将确保文本字段仅包含一个小数点和其后仅一个字符。

您可以使用此正则表达式并根据需要创建规则。