每4个添加一个空格,同时限制输入字数

2016-10-13  本文已影响188人  白鹿Divella

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

{

NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容

if (_cardIDtextFiled == textField){

//检测是否为纯数字

if ([self isPureInt:string]) {

//添加空格,每4位之后,4组之后不加空格,格式为xxxx xxxx xxxx xxxx xxxxxxxxxxxxxx

if (textField.text.length % 5 == 4 && textField.text.length < 22) {

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

}

//只要30位数字

if ([toBeString length] >= 19+4+11)

{

toBeString = [toBeString substringToIndex:19+4+11];

_cardIDtextFiled.text = toBeString;

[_cardIDtextFiled resignFirstResponder];

return NO;

}

}

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

if ((textField.text.length - 2) % 5 == 4 && textField.text.length < 22) {

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

}

return YES;

}

else{

return NO;

}

return YES;

}

return YES;

}

- (BOOL)isPureInt:(NSString *)string{

NSScanner* scan = [NSScanner scannerWithString:string];

int val;

return [scan scanInt:&val] && [scan isAtEnd];

}

上一篇下一篇

猜你喜欢

热点阅读