I need to make sure that the user is only entering numbers into my textfield. I have the keyboard set to numbers, but if the user is using an external keyboard they might enter a letter. How can I detect if any characters in my textfield.text are characters instead of numbers?
Thanks!
You can choose what characters can input into the 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With