iOS 关于文本框忽略特殊字符的问题

时间:2022-11-02 19:48:26

相信很多人遇到这样的问题:登录注册或者修改密码时,尤其是设定密码时候,不想用空格、特殊字符等这类的字符,但要怎么做呢?其实很简单:

在UITextField的delegate方法中设置一下就OK了,是不是很简单?

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_//|~<>$€^£•'@#$%^&*():;.,?!<>\\_+'/\""];
NSString *str = [tem stringByTrimmingCharactersInSet:set];
if (![string isEqualToString:str]) {
return NO;

}
return YES;
}