銀行卡輸入每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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章