输入框显示银行卡格式,即为每隔4位出现一个空格, 下面使用UITextFieldDelegate,编码实现: 首先引用使用代理
代码语言:javascript复制类名 ()<UITextFieldDelegate>
代码语言:javascript复制self.textField.delegate = self;
使用代理方法
代码语言:javascript复制- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.contentTextField) {
// 4位分隔银行卡卡号
NSString *text = [textField text];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789b"];
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 显示银行卡格式。