UITextField 文字限制 长度限制(包含高亮) 特殊字符限制

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

  //表情
  if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
      return NO;
      
  }
  NSString *newString = [self.inputField.text stringByReplacingCharactersInRange:range withString:string];
  
  NSString *other = @"➋➌➍➎➏➐➑➒";
  
  if (([self hasIllegalCharacter:string]&&!([other rangeOfString:
                                             string].location != NSNotFound))) {
      
      return NO;
  }
  
  NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; // 键盘输入模
  
  if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,
      
      UITextRange *selectedRange = [textField markedTextRange];
      //获取高亮部分
      NSString * newText = [textField textInRange:selectedRange];
      NSInteger realLength = newString.length - newText.length;
      //这个空格不是普通的空格 ,这个空格取自高亮字符串中间的空格(粘贴过来的,否则匹配不上)
      NSString *gaolingtext = [newText stringByReplacingOccurrencesOfString:@" " withString:@""];
      realLength = realLength+gaolingtext.length;
      if (newText.length>0) {
          if (realLength > self.maxCount)
          {
              [[UTHudUtil shareInstance] toggleMessageInViewCenter:[NSString stringWithFormat:@"最多输入%ld个字符",self.maxCount]];
              return NO;
          }
      }else
      {
          if (newString.length>self.maxCount&&self.maxCount>0) {
              
              [[UTHudUtil shareInstance] toggleMessageInViewCenter:[NSString stringWithFormat:@"最多输入%ld个字符",self.maxCount]];
              
              return NO;
          }
      }
  }else
  {
      if (newString.length>self.maxCount&&self.maxCount>0) {
          
          [[UTHudUtil shareInstance] toggleMessageInViewCenter:[NSString stringWithFormat:@"最多输入%ld个字符",self.maxCount]];
          
          return NO;
      }
  }
  return YES;

}


- (BOOL)hasIllegalCharacter:(NSString *)content {
  
  //提示标签不能输入特殊字符
  
  if ([content containsString:@"\n"]||[content isEqualToString:@""]) {
      
      return NO;
  }
  NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
  
  NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
  
  if (![emailTest evaluateWithObject:content]) {
      
      return YES;
      
  }
  
  return NO;


}

你可能感兴趣的:(UITextField 文字限制 长度限制(包含高亮) 特殊字符限制)