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.t开发者_开发百科ext
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;
}
Whenever the user enters a key this textfield delegate will be called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Inside this check whether the text contains characters. if it is do your action. like promptimg a alert or something.
Implement textField:shouldChangeCharactersInRange:replacementString:
in the text field's delegate and return NO
if the passed string contains invalid characters.
精彩评论