限制UITextfield的输入字符为50个字符

1.实现UITextfieldDelegate

2.在UITextfield的代理方法中判断添加字符还是删除字符,从而做不同的操作

#pragma mark-UITextfield的代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger index = range.location + range.length;
    if (index < 50) {
        return YES;
    } else {
        //判断临界值的时候是添加文字还是删除文字
        if (string.length==0) {
            //删除文字
            return YES;
        }
        
        //当location==50 string.length>0时需要提示
        
        [MBProgressHUD showError:@"输入的字符长度不能超过50"];
        return NO;
    }
}

猜你喜欢

转载自www.cnblogs.com/wobuyayi/p/9469770.html