iOS-银行卡四位数分隔效果

#pragma UITextFieldDelegate实现输入位数出现一个空格

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

    NSString *text = [textField 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:@""];

    if ([text length] >= 21) {

       return NO;

    }


   NSString *newString =@"";

   while (text.length >0) {

       NSString *subString = [textsubstringToIndex: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]];

    [textFieldsetText:newString];

    return NO;

}

你可能感兴趣的:(iOS-银行卡四位数分隔效果)