6

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

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

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

4

10 回答 10

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;
}
于 2011-11-18T08:16:29.387 回答
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);

}
于 2012-12-11T01:49:32.940 回答
4

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

  • 用户应该只能输入 0-9 和 decimal 。人物
  • 只有一位小数。允许的字符
  • 小数点前最多 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;
}
于 2016-03-14T11:51:06.817 回答
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;
}
于 2012-04-04T16:02:27.947 回答
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;
        }
于 2013-07-24T12:51:20.483 回答
1

听起来你需要一个NSNumberFormatter

于 2011-11-10T07:47:37.640 回答
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 
}
于 2016-08-17T05:31:17.433 回答
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。

于 2013-12-03T02:56:14.060 回答
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
}
于 2014-04-02T02:29:47.877 回答
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;
 }

上面的代码将确保文本字段只包含一个小数点,并且在它之后只包含一个字符。

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

于 2018-07-25T08:06:12.633 回答