Reputation: 411
I want a UITextField
to allow only alphabets.SpecialCharacters(@,!,,,)
and numbers are not allowed.So thought of restricting the keyboard type to txtfirstname.keyboardType = UIKeyboardTypeAlphabet;
-(void)viewDidLoad{
txtfirstname.keyboardType = UIKeyboardTypeAlphabet;
}
But when I press numbers then also they are getting entered in textfield.Why is it so?
When a number or special character is pressed in txtfirstname
then it should get entered in textfield.
How can I do it?
Upvotes: 0
Views: 141
Reputation: 92
Here use below function...Mention what do you need the characters in NSCharacterSet..
-(NSString *) formatIdentificationNumber:(NSString *)string
{
NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"àáâäæãåçćčèéêëęėîïìíįłñńôöòóõœøßśšûüùúŵŷÿźžż°§¿’‘€$£¥₩\n1234567890"];
NSString * result = @"";
NSScanner * scanner = [NSScanner scannerWithString:string];
NSString * scannerResult;
[scanner setCharactersToBeSkipped:nil];
while (![scanner isAtEnd])
{
if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
{
result = [result stringByAppendingString:scannerResult];
}else
{
if(![scanner isAtEnd])
{
[scanner setScanLocation:[scanner scanLocation]+1];
}
}
}
return result;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(![string isEqualToString:@""])
{
if(textField == textfieldname)
{
if ([[self formatIdentificationNumber:string] isEqualToString:@""] && ![string isEqualToString:@""]) {
return NO;
}
}
Upvotes: 1
Reputation: 3754
try this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
static NSCharacterSet *charSet2 = nil;
if(!charSet2)
{
charSet2 = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./,':+_)\(*~`=&^%$#@!,-?<>\"{}][| "] invertedSet];
}
NSRange location = [string rangeOfCharacterFromSet:charSet2];
return (location.location == NSNotFound);
}
Upvotes: 0