ios-为银行卡号格式化 每隔四位添加一个空格

-(NSString *)formatterBankCardNum:(NSString *)string

{

    NSString *tempStr=string;

    

    

    NSInteger size =(tempStr.length / 4);

    

    NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];

    for (int n = 0;n < size; n++)

    {

        [tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(n*4, 4)]];

    }

    

    [tmpStrArr addObject:[tempStr substringWithRange:NSMakeRange(size*4, (tempStr.length % 4))]];

    

    tempStr = [tmpStrArr componentsJoinedByString:@" "];

    

    return tempStr;

    

}

----------------------------------textfield代理实现每隔四位添加空格-------------------------------------

-(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:@""];

    

    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)

    {

        [_textFieldBankCardNumber resignFirstResponder];

        return NO;

    }

    

    [textField setText:newString];

    _textFieldBankCardNumber.text=textField.text;

    return NO;

}

 

posted @ 2014-12-17 16:58  曹县三胖暴打大猩猩  阅读(2152)  评论(0编辑  收藏  举报