Fork me on GitHub

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;

        }

   }

}

 

posted @ 2019-08-30 15:49  平凡的不平凡  阅读(2748)  评论(0编辑  收藏  举报
AmazingCounters.com