textfield输入文本长度限制(超出后不能输入)

第一步 新建textfield

 _tf=[[UITextField alloc]initWithFrame:CGRectMake(50, 150, 200, 30)];

    _tf.backgroundColor=[UIColor whiteColor];

    _tf.delegate=self;//开代理

    _tf.autocapitalizationType = UITextAutocapitalizationTypeNone;

    [self.view addSubview:_tf];


第二步 ,为textfield开监听方法

 [_tf addTarget:self action:@selector(infoAction:) forControlEvents:UIControlEventEditingChanged];


//实现监听

- (void)infoAction:(UITextField *)textField

{

    NSString *toBeString = textField.text;

    UITextRange *selectedRange = [textField markedTextRange];

    //获取高亮部分

    NSString *newText=[textField textInRange:selectedRange];

    if (newText.length>0) {

        return; //如果存在高亮部分则此时不计算textfield的文字长度

    }else{

        if ([self textLength:toBeString] >16) {

            NSUInteger asciiLength = 0;

            

            for (NSUInteger i = 0; i <textField.text.length; i++) {

                unichar uc = [textField.text characterAtIndex: i];

                asciiLength += isascii(uc) ? 1 : 2;

                if (asciiLength==16) {

                    textField.text = [textField.text substringToIndex:i+1];

                    return;

                }

                if (asciiLength>16) {

                    textField.text = [textField.text substringToIndex:i];

                    return;

                }

            }

        }   

    }

}


第三步 设置代理方法

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if (self.tf == textField){

        UITextRange *selectedRange = [textField markedTextRange];

        NSString *newText=[textField textInRange:selectedRange];

        if (newText.length>0) {

            return YES;

        }else{

        if (string.length == 0) return YES;

        NSUInteger existedLength =[self textLength:textField.text];

        NSUInteger selectedLength = range.length;

        NSUInteger replaceLength = string.length;

        if (existedLength - selectedLength + replaceLength > 16) {

                return NO;

            }

        }

    }

   return YES;

}

//判断字符串长度(汉字两字节)

-(NSUInteger)textLength: (NSString *) text{

    

    NSUInteger asciiLength = 0;

    

    for (NSUInteger i = 0; i < text.length; i++) {

        

        

        unichar uc = [text characterAtIndex: i];

        

        asciiLength += isascii(uc) ? 1 : 2;

    }

    

    NSUInteger unicodeLength = asciiLength;

    

    return unicodeLength;

    

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值