IOS TextField 输入银行卡号格式化(每四位中间空一格)

最近做的项目有关于银行卡号输入的情景设定,参照微信绑卡操作,输入卡号数字每隔4位空1位。

IOS TextField 输入银行卡号格式化(每四位中间空一格)_第1张图片

由于赶进度,没细作研究,特此网上摘录的代码片段,如下:


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.text_cardno) {
        NSString *text = [self.text_cardno 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.text_cardno setText:newString];
        
        return NO;
        
    }
    return YES;
}

// 银行卡号转正常号 - 去除4位间的空格
-(NSString *)bankNumToNormalNum
{
    return [self.text_cardno.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}

转自

http://blog.csdn.net/h3c4lenovo/article/details/8515304

你可能感兴趣的:(iOS)