iOS UITextField、UITextView只限输入中文、英文、数字及实时限制字符个数的封装实现代码

时间:2022-06-26 14:03:08

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

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

iOS UITextField、UITextView只限输入中文、英文、数字及实时限制字符个数的封装实现代码

直接上代码

一、注册通知

?
1
2
[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(textfieldchange:) name:uitextfieldtextdidchangenotification object:nil];
[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(textfieldchange:) name:uitextviewtextdidchangenotification object:nil];

二、通知实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (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

?
1
2
3
4
5
#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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#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只限输入中文、英文、数字及实时限制字符个数封装实现,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/yj_sail/article/details/53928940