UITextfield限制文字2~6或字符4~12

//判断当前文字字符长度的方法
-(NSUInteger) unicodeLengthOfString: (NSString *) text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}
//代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSLog(@"text---->>%@",text);

    NSInteger length=[self unicodeLengthOfString:text];
    
    NSLog(@"%ld",(long)length);

    if (length > 12)
    {
        return NO;
    }
    
    return YES;
}
这样功能就实现了,超过长度后就不能输入字符了。

你可能感兴趣的:(UITextfield限制文字2~6或字符4~12)