美文网首页
银行卡号格式化

银行卡号格式化

作者: kysonyangs | 来源:发表于2016-01-19 17:37 被阅读838次

    在输入银行卡号过程中,每隔4位插入一个"-",类似"1332-2131-2313-1231-212"这种的
    做法:

    1. 设置textField的代理
    2. 在以下代理方法中加入如下方法:
    - (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) {
            return NO;
        }
        
        [textField setText:newString];
        
        return NO;
    }
    
    
    1. 得到不包含"-"的卡号
    [self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""]
    

    OK!

    相关文章

      网友评论

          本文标题:银行卡号格式化

          本文链接:https://www.haomeiwen.com/subject/uczkkttx.html