银行卡追加字符

2017-01-14  本文已影响9人  ISwiftUI

关于银行卡显示和输入的处理

// 指定位数追加字符
+ (NSString *) addSpaceWithStr:(NSString *)str toStr:(NSString *) toStr length:(NSInteger) number {
    if (str.length <= number) {
        return str;
    }
    NSMutableString *subStr = [[NSMutableString alloc]initWithString:str];
    // 如果可以整除,最前面则不添加
    NSInteger index = (str.length / number - 1);
    for (int i = 0; i < index; i++) {
        // 开始追加字符
        [subStr insertString:toStr atIndex:(subStr.length - (i * (number + toStr.length) + number))];
    }
    return subStr;
}


// 只保留后四位数字,其它位用星号替代
- (NSString *) charcterWithStar:(NSString *) str {
    if (str.length <= 4) {
        return str;
    }
    NSMutableString *mutStr = [NSMutableString new];
    NSString *firstStr = [str substringWithRange:NSMakeRange(0,str.length - 4)];
    NSString *secondStr = [str substringWithRange:NSMakeRange(str.length - 4,4)];
    NSMutableString *starStr = [NSMutableString new];
    for (int i = 0; i <= firstStr.length - 1; i++) {
         [starStr appendString:@"*"];
    }
    firstStr = [firstStr stringByReplacingOccurrencesOfString:[firstStr substringWithRange:NSMakeRange(0,firstStr.length)]withString:starStr];
    [mutStr appendString:firstStr];
    [mutStr appendString:secondStr];
    return mutStr;
}

// 移除字符串中的所有空格
- (NSString *) removeStrAllSpace:(NSString *)str {
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return str;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 四位加一个空格
    if ([string isEqualToString:@""])  { // 删除字符
        if ((textField.text.length - 2) % 5 == 0) {
           textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
    return YES;
    } else {
        if (textField.text.length % 5 == 0) {
            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
       }
    }
    return YES;
}
上一篇下一篇

猜你喜欢

热点阅读