-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:@" "] || [string isEqualToString:@"@"] || [string isEqualToString:@"!"] || [string isEqualToString:@"#"] || [string isEqualToString:@"$"] || [string isEqualToString:@"%"] || [string isEqualToString:@"^"] || [string isEqualToString:@"&"] || [string isEqualToString:@"*"] || [string isEqualToString:@"("] || [string isEqualToString:@")"] || [string isEqualToString:@"+"] || [string isEqualToString:@"-"])
return NO;
return YES;
}
I am using this method to restrict all these characters. It works fine when user types text from keyboard. If user paste text or use siri to enter text nothing happens.
How to fix it.
Try to customize your delegate method like this:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:@" "] || [string isEqualToString:@"@"] || [string isEqualToString:@"!"] || [string isEqualToString:@"#"] || [string isEqualToString:@"$"] || [string isEqualToString:@"%"] || [string isEqualToString:@"^"] || [string isEqualToString:@"&"] || [string isEqualToString:@"*"] || [string isEqualToString:@"("] || [string isEqualToString:@")"] || [string isEqualToString:@"+"] || [string isEqualToString:@"-"])
{
return NO;
}
else if([string length] > 1)
{
NSCharacterSet *notAllowedChars = [NSCharacterSet characterSetWithCharactersInString:@"@!!#$%^&*()+-@%"];
NSString *resultString = [[string componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
textField.text = resultString;
return NO;
}
return YES;
}