iOS TextField限制字数功能,无需截取,体验较好,类似微信相应功能,如编辑标签等

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

{    
    NSInteger maxLength = 7;

    NSMutableString *stringTarget = [NSMutableString string];

    NSString *alreadyExistString = [textField.text substringToIndex:range.location];

    [stringTarget appendString:alreadyExistString];

    if (range.length != 0) {
        [stringTarget appendString:string];
    }
    else {

        // 此处必须包含等于
        if (stringTarget.length >= maxLength && string.length != 0) {
            return NO;
        }
        else {
            [stringTarget appendString:[textField.text substringFromIndex:range.location]];
        }
    }

    // 会出现一种情况,就是当你输入完一些字以后,系统自动给出智能提示的字供 选择,此时不符合以上逻辑
    // 这里做一些防错处理
    if (range.location + string.length > maxLength) {
        return NO;
    }

    if (stringTarget.length > maxLength && string.length != 0) {
        return NO;
    }

    return YES;

}

你可能感兴趣的:(iOS TextField限制字数功能,无需截取,体验较好,类似微信相应功能,如编辑标签等)