UITextField Should accept number only values

前端 未结 14 1249
有刺的猬
有刺的猬 2020-12-08 09:50

I have UITexfields i want that it should accept only number other shows alert that enter a numeric value. I want that motionSicknessTextFiled should only accept number

14条回答
  •  情歌与酒
    2020-12-08 10:27

    I just modified the answer of Michael and made it a little bit easier to implement. Just make sure that the delegate of your UITextfield is set to itself.

    yourTxtField.delegate = self;
    

    Furthermore copy & paste this code into your main file.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    
        if (textField == yourTxtField) {
            NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
            NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
    
            BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
                return stringIsValid;
            }else {
                return YES;
            }
        }
    

    If you want to allow the use of the spacebar just put in a blank space at the end of the CharactersInString, just like so:

    @"0123456789" -> @"0123456789 "
    

    Additionally:

    If you want to restrict the length of the string just replace the if-function with following:

    if (textField == yourTxtField) {
            NSUInteger newLength = [textField.text length] + [string length] - range.length;
            NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
            return (([string isEqualToString:filtered])&&(newLength <= 10));
    
        }
    

    In my case the "10" at the end represents the limit of characters.

    Cheers! :)

提交回复
热议问题