iOS UITextField如何禁止输入表情及特殊字符

---恢复内容开始---

//禁止输入表情

- (NSString *)disable_emoji:(NSString *)text

{

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];

    NSString *modifiedString = [regex stringByReplacingMatchesInString:text

                                                               options:0

                                                                 range:NSMakeRange(0, [text length])

                                                          withTemplate:@"&&&&****"];

    return modifiedString;

}

//使用方式

 

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

    if ([[self disable_emoji:string] isEqualToString:@"&&&&****"] || [[self disable_emoji:string] isEqualToString:@"&&&&****&&&&****"]) {

        [textField becomeFirstResponder];

        [FZPPregressHUD showNormalWithStatus:@"禁止输入特殊字符"];

        return NO;

    }

}

//禁止输入特殊字符

//首先需要先将特殊字符存放在数组内

       self.specialStringArray = [@[] mutableCopy];

       //字符串

        self.specialStringStr = @"~,¥,#,&,*,<,>,《,》,(,),[,],{,},【,】,^,@,/,£,¤,,|,§,¨,「,」,『,』,¢,¬, ̄,(,),——,+,|,$,_,€,¥,?,/,|,,,。,!,!";

        self.specialStringArray = [self.specialStringStr componentsSeparatedByString:@","];

 

//然后还是在代理方法中实现

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

           循环遍历字符串

      for (NSInteger i = 0; i < self.specialStringArray.count; i++) {

        //判断字符串中是否含有特殊符号

        if ([intriduction rangeOfString:self.specialStringArray[i]].location != NSNotFound) {

            [textField becomeFirstResponder];

            [FZPPregressHUD showNormalWithStatus:@"禁止输入特殊字符"];

            textField.text = [textField.text substringToIndex:textField.text.length - 1];

            return NO;

        }

//逗号需要特殊处理一下

        if ([intriduction rangeOfString:@","].location != NSNotFound) {

            [textField becomeFirstResponder];

            [FZPPregressHUD showNormalWithStatus:@"禁止输入特殊字符"];

            textField.text = [textField.text substringToIndex:textField.text.length - 1];

            return NO;

        }

   }

}

 

iOS UITextField如何禁止输入表情及特殊字符

上一篇:ios计时器失效


下一篇:cocoscreator构建的android工程报错