uitextFiled字数输入限制

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

    if (self.type == YXModifyTrueLoveInputTypeNick) {

        NSLog(@"%ld",[self countTheStrLength:[textField.text stringByReplacingCharactersInRange:range withString:string]]);

        NSInteger textLength = [self countTheStrLength:[textField.text stringByReplacingCharactersInRange:range withString:string]];

 

        if (textLength > 4 && string.length > 0) {

            return NO;

        } else {

            self.textLabel.text = [NSString stringWithFormat:@"还可以输入%d个字符",(int)MAX(4 - textLength, 0)];

        }

    }

    return YES;

}

 

- ( NSInteger )countTheStrLength:( NSString *)strtemp {

    NSInteger strlength = 0 ;

    char * p = ( char *)[strtemp cStringUsingEncoding : NSUnicodeStringEncoding ];

    for ( int i= 0 ; i<[strtemp lengthOfBytesUsingEncoding : NSUnicodeStringEncoding ] ;i++) {

        if (*p) {

            p++;

            strlength++;

        }else {

            p++;

        }

    }

    return (strlength+ 1 )/ 2 ;

}

 

posted on 2017-02-24 08:22  芳馨幽兰  阅读(257)  评论(0编辑  收藏  举报

导航