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


    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];
  • 相关阅读:
    多态
    重载 特点
    java 测量运行时间 单位:毫秒
    java 源代码 二分查找 Arrays
    java 同步 synchronized
    云服务器,价格其实不便宜,但为什么还要用呢
    网站访问优化(二):开启apache服务器gzip压缩
    CXF整合Spring开发WebService
    网站访问优化,未完待续
    网站访问优化,未完待续
  • 原文地址:https://www.cnblogs.com/isItOk/p/5591579.html
Copyright © 2020-2023  润新知