规范银行卡输入格式,四位四位输入

xiaoxiao2021-02-28  93

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

    if (textField == _bankCardIDTextField) {

        NSString *text = [_bankCardIDTextField text];

        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];

        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];

        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {

            return NO;

        }

        text = [text stringByReplacingCharactersInRange:range withString:string];

        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

        NSString *newString = @"";

        while (text.length > 0) {

            NSString *subString = [text substringToIndex:MIN(text.length, 4)];

            newString = [newString stringByAppendingString:subString];

            if (subString.length == 4) {

                newString = [newString stringByAppendingString:@" "];

            }

            text = [text substringFromIndex:MIN(text.length, 4)];

        }

        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];

        // 限制长度

        if (newString.length >= 24) {

            return NO;

        }

        [_bankCardIDTextField setText:newString];

        return NO;

    }

    return YES;

}

// 银行卡号转正常号 - 去除4位间的空格

-(NSString *)bankNumToNormalNum

{

    return [_bankCardIDTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

}

转载请注明原文地址: https://www.6miu.com/read-2250188.html

最新回复(0)