How can I limit the number of decimal points in a UITextField?

后端 未结 15 2314
说谎
说谎 2020-12-01 05:20

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal

15条回答
  •  囚心锁ツ
    2020-12-01 06:03

    Implement the shouldChangeCharactersInRange method like this:

    // Only allow one decimal point
    // Example assumes ARC - Implement proper memory management if not using.
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
    {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSArray  *arrayOfString = [newString componentsSeparatedByString:@"."];
    
        if ([arrayOfString count] > 2 ) 
            return NO;
    
        return YES;
    }
    

    This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array.

提交回复
热议问题