I just modified Michael's answer and made it a little easier to implement. Just make sure the delegate of your UITextfield configured for itself.
yourTxtField.delegate = self;
In addition, copy and 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 a space, just put it in the empty space at the end of CharactersInString , as well:
@"0123456789" -> @"0123456789 "
Additionally:
If you want to limit the length of the string, just replace the if function as follows:
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, β10β at the end represents the character limit.
Hurrah!:)
MasterRazer Sep 04 '15 at 23:13 2015-09-04 23:13
source share