IOS UITextfield控制用来输入价格等浮点数

2016-05-08  本文已影响413人  无敌还真是寂寞

+ (BOOL)validateNumber:(NSString*)number text:(NSString *)textFieldText floatCount:(NSInteger)floatCount {

BOOL res = YES;

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

int i = 0;

if (number.length==0) {

//允许删除

return  YES;

}

while (i < number.length) {

//确保是数字

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

NSRange range = [string rangeOfCharacterFromSet:tmpSet];

if (range.length == 0) {

res = NO;

break;

}

i++;

}

if (textFieldText.length==0) {

//第一个不能是0和.

if ([number isEqualToString:@"0"]||[number isEqualToString:@"."]) {

return NO;

}

}

NSArray *array = [textFieldText componentsSeparatedByString:@"."];

NSInteger count = [array count] ;

//小数点只能有一个

if (count>1&&[number isEqualToString:@"."]) {

return NO;

}

//控制小数点后面的字数

if ([textFieldText rangeOfString:@"."].location!=NSNotFound) {

if (textFieldText.length-[textFieldText rangeOfString:@"."].location>floatCount) {

return NO;

}

}

return res;

}

调用:

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

if (textField==degreeTextField) {

return [CommanTool validateNumber:string text:textField.text floatCount:1];

}

return YES;

}

上一篇下一篇

猜你喜欢

热点阅读