限制输入长度并只能输入数字

//限制输入长度并只能输入数字

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

if (textField == self.numberTextF) {

//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.

if (range.length == 1 && string.length == 0) {

return YES;

}

//so easy

else if (self.numberTextF.text.length >= 8) {

self.numberTextF.text = [textField.text substringToIndex:8];

return NO;

}

}

return [self validateNumber:string];

}

- (BOOL)validateNumber:(NSString*)number {

BOOL res = YES;

NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

int i = 0;

while (i < number.length) {

NSString * string = [number substringWithRange:NSMakeRange(i, 1)];

NSRange range = [string rangeOfCharacterFromSet:tmpSet];

if (range.length == 0) {

res = NO;

break;

}

i++;

}

return res;

}


//限制输入长度并只能输入数字和小数

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

if (textField == self.numberTextF) {

if ([textField.text rangeOfString:@"."].location==NSNotFound) {

_isHaveDian = NO;

}

if ([textField.text rangeOfString:@"0"].location==NSNotFound) {

_isFirstZero = NO;

}

if ([string length]>0) {

//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.

if (range.length == 1 && string.length == 0) {

return YES;

}

//so easy

else if (self.numberTextF.text.length >= 8) {

self.numberTextF.text = [textField.text substringToIndex:8];

return NO;

}

//当前输入的字符

unichar single=[string characterAtIndex:0];

//数据格式正确

if ((single >='0' && single<='9') || single=='.') {

if([textField.text length]==0){

if(single == '.'){

//首字母不能为小数点

return NO;

}

if (single == '0') {

_isFirstZero = YES;

return YES;

}

}

if (single=='.') {

//text中还没有小数点

if(!_isHaveDian) {

_isHaveDian=YES;

return YES;

}else{

return NO;

}

}else if(single=='0') {

if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {

//首位有0有.(0.01)或首位没0有.(10200.00)可输入两位数的0

if([textField.text isEqualToString:@"0.0"]){

return NO;

}

NSRange ran=[textField.text rangeOfString:@"."];

int tt=(int)(range.location-ran.location);

if (tt <= 2){

return YES;

}else{

return NO;

}

}else if (_isFirstZero&&!_isHaveDian){

//首位有0没.不能再输入0

return NO;

}else{

return YES;

}

}else {

if (_isHaveDian) {

//存在小数点,保留两位小数

NSRange ran=[textField.text rangeOfString:@"."];

int tt= (int)(range.location-ran.location);

if (tt <= 2){

return YES;

}else{

return NO;

}

}else if(_isFirstZero&&!_isHaveDian){

//首位有0没点

return NO;

}else{

return YES;

}

}

}else{

//输入的数据格式不正确

return NO;

}

}else {

return YES;

}

}

return YES;

}

你可能感兴趣的:(限制输入长度并只能输入数字)