iOS常用技术 — UItextfield 限制字数

实现的方法其实有很多,有好,有坏。最好的是方法二,方法一和三是自己在实现该功能时摸索着写的。

另外,UITextView也有相似的代理方法

添加UITextFieldDelegate,将textField的delegate赋给self,即:

textfield.delegate  = self;
  • 方法一
#pragma  mark - uitextfield 的代理方法
//判断 支付密码的字数是否大于8 位 ,小于20,比较low的方法,在输入结束时判断
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 2) {  //判断是tag=2的textfield的内容长度

    if (textField.text.length < 8) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"新支付密码的长度至少为8位" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show]; //给出提示
           textField.text  = @"” ;  //将内容置空,变相清除textfield的内容
    } else if(textField.text.length >20) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"新支付密码的长度不能超过20位" delegate:self  cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
      textField.text  = @"" ;
    }

    }
}
  • 方法二
    到达限制长度后,无论用户再怎么输入,只显示限制长度内的字符
#pragma mark -- 实时监控字符的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location >=8)
        return NO; // 返回no,则textfield文本不在改变
    return YES; //textfield文本还可以变化,即可以再输入
}
  • 方法三
    同方法二一样,到达限制长度后,无论用户再怎么输入,只显示限制长度内的字符
#pragma mark - 字数限制
- (void)textViewDidChange:(UITextView *)textView{

    if ([textView.text length] > 100)
    {

        textView.text = [textView.text substringToIndex:100];

        if (!_isAlert) {
               _isAlert = YES;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"个性签名字数不超过100。" delegate:self
                                                 cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];

        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值