iOS UITextField 顯示銀行卡格式的方法
更新時間:2018年01月09日 14:58:21 作者:FBY展菲
下面小編就為大家分享一篇iOS UITextField 顯示銀行卡格式的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
輸入框顯示銀行卡格式,即為每隔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 顯示銀行卡格式。
這篇iOS UITextField 顯示銀行卡格式的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
淺談Unity中IOS Build Settings選項的作用
下面小編就為大家分享一篇淺談Unity中IOS Build Settings選項的作用,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01

