How to check UITextField text?

I need to make sure that the user only enters numbers in the text box. My keyboard is set to numbers, but if the user uses an external keyboard, they can enter a letter. How can I determine if any characters in my textfield.textcharacters are instead of numbers?

Thank!

+3
source share
3 answers

You can choose which characters can be entered in textField

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

    /*  this ensures that ONLY numbers can be entered, no matter what kind of keyboard is used  */
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }

    /*  this allows you to choose how many characters can be used in the textField  */
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 7) ? NO : YES;
}
+4
source

Whenever a user enters a key, this text field delegate will be called.

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

, . . promptimg - .

+1

Fill textField:shouldChangeCharactersInRange:replacementString:in the delegate text field and return NOif the string passed contains invalid characters.

+1
source

Source: https://habr.com/ru/post/1781044/


All Articles