UITextField : restrict the maximum allowed value (number) during inputting

前端 未结 5 1195
后悔当初
后悔当初 2021-01-03 14:17

I have a UITextField, I\'d like to restrict the maximum allowed input value in the field to be 1000. That\'s when user is inputting number inside, once the inpu

5条回答
  •  余生分开走
    2021-01-03 14:22

    You should do the following inside the above method:

    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    //first, check if the new string is numeric only. If not, return NO;
    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789,."] invertedSet];
    if ([newString rangeOfCharacterFromSet:characterSet].location != NSNotFound)
    {
        return NO;
    }
    
    return [newString doubleValue] < 1000;
    

提交回复
热议问题