iOS UITextField、UITextView只限输入中文、英文、数字

编辑: admin 分类: 苹果教程 发布时间: 2022-03-30 来源:互联网

引言需求:(输入框限制输入多少字符)

1、一个字母、符号、数字相当于一个字符
2、一个汉字相当于两个字符
3、不能输入特殊字符
4、不能输入emoji表情

直接上代码

一、注册通知

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextViewTextDidChangeNotification object:nil];

二、通知实现

- (void)textFieldChange:(UITextField *)textField
{
  //判断输入(不能输入特殊字符)
  [RestrictionInput restrictionInputTextField:self.titleTextField maxNumber:100 showView:self showErrorMessage:@"商品名称0~100字符~"];
  [RestrictionInput restrictionInputTextView:self.infoTextView maxNumber:200 showView:self showErrorMessage:@"商品描述0~200字符~"];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
  if ([RestrictionInput isInputRuleAndBlank:text] || [text isEqualToString:@""]) {//当输入符合规则和退格键时允许改变输入框
    return YES;
  } else {
    return NO;
  }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  if ([RestrictionInput isInputRuleAndBlank:string] || [string isEqualToString:@""]) {//当输入符合规则和退格键时允许改变输入框
    return YES;
  } else {
    return NO;
  }
}

三、封装类(RestrictionInput)

.h

#import <Foundation/Foundation.h>
@interface RestrictionInput : NSObject
+ (void)restrictionInputTextField:(UITextField *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage;
+ (void)restrictionInputTextView:(UITextView *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage;
+ (BOOL)isInputRuleAndBlank:(NSString *)str;

.m

#import "RestrictionInput.h"
@implementation RestrictionInput
+ (void)restrictionInputTextField:(UITextField *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage
{
  NSString *toBeString = inputClass.text;
  if (![self isInputRuleAndBlank:toBeString]) {
    inputClass.text = [self disable_emoji:toBeString];
    return;
  }
  NSString *lang = [[inputClass textInputMode] primaryLanguage]; // 获取当前键盘输入模式
  if([lang isEqualToString:@"zh-Hans"]) { //简体中文输入,第三方输入法(搜狗)所有模式下都会显示“zh-Hans”
    UITextRange *selectedRange = [inputClass markedTextRange];
    //获取高亮部分
    UITextPosition *position = [inputClass positionFromPosition:selectedRange.start offset:0];
    //没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if(!position) {
      NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber];
      if(getStr && getStr.length > 0) {
        inputClass.text = getStr;
        [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil];
        NSLog(@"%@", inputClass.text);
      }
    }
  } else{
    NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber];
    if(getStr && getStr.length > 0) {
      inputClass.text= getStr;
      [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil];
      NSLog(@"%@",inputClass.text);
    }
  }
}
+ (void)restrictionInputTextView:(UITextView *)inputClass maxNumber:(NSInteger)maxNumber showView:(UIView *)showView showErrorMessage:(NSString *)errorMessage
{
  NSString *toBeString = inputClass.text;
  if (![self isInputRuleAndBlank:toBeString]) {
    inputClass.text = [self disable_emoji:toBeString];
    return;
  }
  NSString *lang = [[inputClass textInputMode] primaryLanguage]; // 获取当前键盘输入模式
  if([lang isEqualToString:@"zh-Hans"]) { //简体中文输入,第三方输入法(搜狗)所有模式下都会显示“zh-Hans”
    UITextRange *selectedRange = [inputClass markedTextRange];
    //获取高亮部分
    UITextPosition *position = [inputClass positionFromPosition:selectedRange.start offset:0];
    //没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if(!position) {
      NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber];
      if(getStr && getStr.length > 0) {
        inputClass.text = getStr;
        [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil];
        NSLog(@"%@", inputClass.text);
      }
    }
  } else{
    NSString *getStr = [self getSubString:toBeString maxNumber:maxNumber];
    if(getStr && getStr.length > 0) {
      inputClass.text= getStr;
      [showView showHudText:errorMessage hideDelay:1.0 completionBlock:nil];
      NSLog(@"%@",inputClass.text);
    }
  }
}
/**
 * 获得 kMaxLength长度的字符
 */
+ (NSString *)getSubString:(NSString*)string maxNumber:(NSInteger)maxNumber
{
  NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
  NSData* data = [string dataUsingEncoding:encoding];
  NSInteger length = [data length];
  if (length > maxNumber) {
    NSData *data1 = [data subdataWithRange:NSMakeRange(0, maxNumber)];
    NSString *content = [[NSString alloc] initWithData:data1 encoding:encoding];//【注意4】:当截取kMaxLength长度字符时把中文字符截断返回的content会是nil
    if (!content || content.length == 0) {
      data1 = [data subdataWithRange:NSMakeRange(0, maxNumber - 1)];
      content = [[NSString alloc] initWithData:data1 encoding:encoding];
    }
    return content;
  }
  return nil;
}
/**
 * 字母、数字、中文正则判断(不包括空格)
 */
+ (BOOL)isInputRuleNotBlank:(NSString *)str {
  NSString *pattern = @"^[➋➌➍➎➏➐➑➒\a-zA-Z\u4E00-\u9FA5\\d]*$";
  NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  BOOL isMatch = [pred evaluateWithObject:str];
  return isMatch;
}
/**
 * 字母、数字、中文正则判断(包括空格)【注意3】
 */
+ (BOOL)isInputRuleAndBlank:(NSString *)str {
  //九宫格无法输入解决需要加上正则 \➋➌➍➎➏➐➑➒
  NSString *pattern = @"^[➋➌➍➎➏➐➑➒\a-zA-Z\u4E00-\u9FA5\\d\\s]*$";
  NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  BOOL isMatch = [pred evaluateWithObject:str];
  return isMatch;
}
+ (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;
}

以上所述是小编给大家介绍的iOS UITextField、UITextView只限输入中文、英文、数字及实时限制字符个数封装实现,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对海外IDC网网站的支持!

【本文来源:韩国服务器 http://www.558idc.com/kt.html欢迎留下您的宝贵建议】