首页 > 其他 > 详细

uitextfield动态限制输入的字数-b

时间:2016-06-16 17:44:50      阅读:156      评论:0      收藏:0      [点我收藏+]

1、定义一个事件:

 

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
-(IBAction)limitLength:(UITextField *)sender
{
    bool isChinese;//判断当前输入法是否是中文
    if ([[[UITextInputMode currentInputMode] primaryLanguage] isEqualToString: @"en-US"]) {
        isChinese = false;
    }
    else
    {
        isChinese = true;
    }
     
    if(sender == self.txtName) {
        // 8位
        NSString *str = [[self.txtName text] stringByReplacingOccurrencesOfString:@"?" withString:@""];
        if (isChinese) { //中文输入法下
                UITextRange *selectedRange = [self.txtName markedTextRange];
                //获取高亮部分
                UITextPosition *position = [self.txtName positionFromPosition:selectedRange.start offset:0];
                // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
                if (!position) {
                    NSLog(@"汉字");
                    if ( str.length>=9) {
                        NSString *strNew = [NSString stringWithString:str];
                        [self.txtName setText:[strNew substringToIndex:8]];
                    }
                }
                else
                {
                    NSLog(@"输入的英文还没有转化为汉字的状态");
                 
                }
        }else{
            NSLog(@"str=%@; 本次长度=%d",str,[str length]);
            if ([str length]>=9) {
                NSString *strNew = [NSString stringWithString:str];
                [self.txtName setText:[strNew substringToIndex:8]];
            }
        }
    }
}


2、对UITextField控件添加监听事件:

 

 

1
2
//UIControlEventEditingChanged
[self.txtName addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];

uitextfield动态限制输入的字数-b

原文:http://www.cnblogs.com/isItOk/p/5591579.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!