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