美文网首页
IOS UITextfield控制用来输入价格等浮点数

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

作者: 无敌还真是寂寞 | 来源:发表于2016-05-08 20:41 被阅读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;

    }

    相关文章

      网友评论

          本文标题:IOS UITextfield控制用来输入价格等浮点数

          本文链接:https://www.haomeiwen.com/subject/fpbdrttx.html