银行卡号格式化
2016-01-19 本文已影响838人
kysonyangs
在输入银行卡号过程中,每隔4位插入一个"-",类似"1332-2131-2313-1231-212"这种的
做法:
- 设置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) {
return NO;
}
[textField setText:newString];
return NO;
}
- 得到不包含"-"的卡号
[self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""]
OK!