zoukankan      html  css  js  c++  java
  • UItextfield 动态限制输入的字数

    @property (nonatomic, strong) UITextField *txtName;

    - (void)viewDidLoad {

        [super viewDidLoad];

    //UIControlEventEditingChanged(包括中文和英文等输入法)
    [self.txtName addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];

    }

    //包括中文和英文等输入法判断,不然会因为联想记忆而崩溃

    -(void)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]];
                }
            }
        }
    }
  • 相关阅读:
    hdu acm 2844 Coins 解题报告
    hdu 1963 Investment 解题报告
    codeforces 454B. Little Pony and Sort by Shift 解题报告
    广大暑假训练1 E题 Paid Roads(poj 3411) 解题报告
    hdu acm 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
    hdu acm 1114 Piggy-Bank 解题报告
    poj 2531 Network Saboteur 解题报告
    数据库范式
    ngnix 配置CI框架 与 CI的简单使用
    Vundle的安装
  • 原文地址:https://www.cnblogs.com/niexiaobo/p/4597958.html
Copyright © 2011-2022 走看看