您的位置:首页 > 产品设计 > UI/UE

关于如何限定UITextField只能输入一个小数点的代码

2016-09-06 12:33 489 查看
当我们在做支付的时候,有时候需要对输入的的数字进行限制,其中就有对小数点的限制,只能输入一个小数点

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

{

    /*

     1.start with zero 0000.....was forbiden

     2.have no '.' & the first character is not '0'

     3.limit the count of '.'

     4.if the first character is '0',then the next one must be '.'

     5.condition like "0.0.0"was forbiden

     6.limit the num of zero after '.'

     */

    if(((string.intValue<0) || (string.intValue>9))){

        //MyLog(@"====%@",string);

        if ((![string
isEqualToString:@"."])) {

            return
NO;

        }

        return NO;

    }

    NSMutableString * futureString = [NSMutableString
stringWithString:textField.text];

    [futureString  insertString:string
atIndex:range.location];

    

    NSInteger dotNum = 0;

    NSInteger flag=0;

    const NSInteger limited = 2;

    if((int)futureString.length>=1){

        

        if([futureString
characterAtIndex:0] == '.'){//the first character can't be '.'

            return
NO;

        }

        if((int)futureString.length>=2){//if
the first character is '0',the next one must be '.'

            if(([futureString
characterAtIndex:1] != '.'&&[futureString characterAtIndex:0] == '0')){

                return
NO;

            }

        }

    }

    NSInteger dotAfter = 0;

    for (int i = (int)futureString.length-1; i>=0; i--) {

        if ([futureString
characterAtIndex:i] == '.') {

            dotNum ++;

            dotAfter = flag+1;

            if (flag > limited) {

                return
NO;

            }

            if(dotNum>1){

                return
NO;

            }

        }

        flag++;

    }

    if(futureString.length - dotAfter > 7){

        //[MBProgressHUD toastMessage:@"超出最大金额"];

        return NO;

    }

    return
YES;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐