输入框显示银行卡格式,即为每隔4位出现一个空格,
下面使用UITextFieldDelegate,编码实现:
首先引用使用代理
类名 ()<UITextFieldDelegate>
self.textField.delegate = self;
使用代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.contentTextField) {
// 4位分隔银行卡卡号
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:@""];
NSLog(@"%@",text);
// text为输入框内的文本,没有“ ”的内容
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 stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 21) {
return NO;
}
[textField setText:newString];
return NO;
}
return YES;
}
使用以上方法即可实现UITextField 显示银行卡格式。
希望可以帮助大家
如果哪里有什么不对或者不足的地方,还望读者多多提意见或建议