明天做格式化銀行卡,防止反復造輪子,找度娘查了下,看到一個不錯的完成方式,記載上去,並附帶完成思緒
#pragma mark - UITextFieldDelegate UITextField鍵入字符後調用
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//拿到為改動前的字符串
NSString *text = [textField text];
//鍵入字符集,\b標示刪除鍵
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
//對以後鍵入字符停止空格過濾
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//invertedSet會對以後後果集取反,反省以後鍵入字符能否在字符集合中,假如不在則直接前往NO 不改動textField值
if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
return NO;
}
//添加以後鍵入字符在改動前的字符串尾部
text = [text stringByReplacingCharactersInRange:range withString:string];
//再次確認去掉字符串中空格
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
//初始化字符用來保管格式化後的字符串
NSString *newString = @"";
//while中對text停止格式化
while (text.length > 0) {
//按4位字符停止截取,假如以後字符缺乏4位則依照以後字符串的最大長度截取
NSString *subString = [text substringToIndex:MIN(text.length, 4)];
//將截取後的字符放入需求格式化的字符串中
newString = [newString stringByAppendingString:subString];
if (subString.length == 4) {
//截取的字符串長度滿4位則在前面添加一個空格符
newString = [newString stringByAppendingString:@" "];
}
//將text中截取掉字符串去掉
text = [text substringFromIndex:MIN(text.length, 4)];
}
//再次確認過濾掉除指定字符以外的字符
newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
//國際銀行卡普通為16~19位 格式化後添加4個空格 也就是最多23個字符
if (newString.length > 23) {
return NO;
}
//手動對textField賦值
[textField setText:newString];
//前往NO 則不經過委托自動往以後字符前面添加字符,到達格式化效果
return NO;
}
【iOS 中 運用UITextField格式化銀行卡號碼的處理方案】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!