1. 程式人生 > >銀行卡輸入自動斷開 如1111 2222 3333 444

銀行卡輸入自動斷開 如1111 2222 3333 444

代理就不用多說了
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
            NSString *text = [textField text];
            
            NSCharacterSet *characterSet =
            [NSCharacterSet characterSetWithCharactersInString:@"0123456789\n"];
            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;
            }
            
            [textField setText:newString];
            
            return NO;
}

1111 2222 3333 444