天天看点

iOS开发笔记- 格式化银行卡号

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

    if (textField.tag == 3333) {

        NSString *text = [self.fieldCardNum 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;

        }

        [self.fieldCardNum setText:newString];

        return NO;

    }

    return YES;

}