1. 程式人生 > >銀行卡輸入每4位自動加空格

銀行卡輸入每4位自動加空格

監聽textField 輸入值的變化

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeAction:) name:UITextFieldTextDidChangeNotification object:nil];

在通知方法中對輸入的值進行改變如下:

- (void)textFieldTextDidChangeAction:(NSNotification *)notification {
    UITextField *textField = notification.object
; if (textField == self.bankCardField) { NSMutableString *text = [NSMutableString stringWithString:textField.text]; //預防輸入空格 替換空格 [text replaceOccurrencesOfString:@" " withString:@"" options:0 range:NSMakeRange(0, text.length)]; NSInteger count;//記錄空格數 if (text.length
% 4 == 0) { count = text.length/4 - 1; } else { count = text.length/4; } for (int i = 0; i < count; i++) { //在指定位置插入空格 [text insertString:@" " atIndex:4 + i*5]; } textField.text = text; } }