美文网首页iOS开发
iOS 判断输入的字符串为格式正确的数字

iOS 判断输入的字符串为格式正确的数字

作者: 杨桃wd | 来源:发表于2017-07-25 12:17 被阅读10次
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([self.moneyTtextField.text rangeOfString:@"."].location==NSNotFound) {
        self.isHaveDian=NO;
    }
    if ([string length]>0){
        unichar single=[string characterAtIndex:0];//当前输入的字符
        
        if([self.moneyTtextField.text length]==0){
              //首字母不能为0和小数点
            if(single =='.'){
                [SVProgressHUD showErrorWithStatus:@"提示,第一个数字不能为小数点"];
                [self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
            if (single =='0') {
                [SVProgressHUD showErrorWithStatus:@"提示,第一个数字不能为0"];
                [self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
        }
        
        if (single=='.'){//text中还没有小数点
            if(!self.isHaveDian){
                self.isHaveDian=YES;
                return YES;
            }else{
                [SVProgressHUD showErrorWithStatus:@"提示,您已经输入过小数点了"];
                [self.moneyTtextField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
        }else{//存在小数点
            if (self.isHaveDian){
                //判断小数点的位数
                NSRange ran=[self.moneyTtextField.text rangeOfString:@"."];
                int tt=range.location-ran.location;
                if (tt <=2){
                    return YES;
                }else{
                    [SVProgressHUD showErrorWithStatus:@"提示,您最多输入两位小数"];
                    return NO;
                }
            }
            else{
                return YES;
            }
        }

    }
    return YES;
}

相关文章

网友评论

    本文标题:iOS 判断输入的字符串为格式正确的数字

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