UITextField四位加一个空格

来源:互联网 发布:chrome 收藏夹mac 编辑:程序博客网 时间:2024/06/07 13:09

_cardTextField=[[UITextFieldalloc]initWithFrame:CGRectMake(40,80, 240, 40)];

_cardTextField.delegate=self;

[self.viewaddSubview:_cardTextField];



#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if (textField == _cardTextField) {

        // 四位加一个空格

        if ([string isEqualToString:@""]) { // 删除字符

            if ((textField.text.length -2) % 5 == 0) {//1234 5

                textField.text = [textField.textsubstringToIndex:textField.text.length -1];

            }

            return YES;

        } else {

            if (textField.text.length %5 == 0) {

                textField.text = [NSStringstringWithFormat:@"%@ ", textField.text];

            }

        }

        return YES;

    }

    return YES;

}

0 0