iOS textField输入限制小数点后两位

不废话,直接上代码!

由于不确定限制位数,设置moneyLength属性来记录位数,初始值最大integer值,可根据自己需求设置为相应位数!

moneyLength = NSIntegerMax;

textField协议:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        
        if([textField.text isEqualToString:@"¥0."]) {
            textField.text = @"";
            return NO;
        }
        
        if(textField.text.length == 1)return NO;
        
        if(textField.text.length == NSIntegerMax)return YES;
        
        if ([textField.text hasSuffix:@"."]) {
            moneyLength = NSIntegerMax;
            return YES;
        }
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (([string isEqualToString:@"0"] && [toBeString isEqualToString:@"¥0"]) || ([string isEqualToString:@"."] && [toBeString isEqualToString:@"¥."])) {
        textField.text = @"¥0.";
        moneyLength = textField.text.length+2;
        return NO;
    }
    
    if ([string isEqualToString:@"."]) {
        if([textField.text containsString:@"."])return NO;
        moneyLength = toBeString.length + 2;
        return YES;
    }
    if ([toBeString length] > moneyLength-1) {
        if(textField.text.length == moneyLength) {
//          可以做相应交互提示
            return NO;
        }
        textField.text = [toBeString substringToIndex:moneyLength];
        return NO;
    }
    return YES;
}

 这种方法适用复杂位数限定,若只有一种固定位数限制推荐下面一种方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([textField.text isEqualToString:@"0."] && string.length == 0) {
            textField.text = @"";
            return NO;
    }

    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (([string isEqualToString:@"0"] || [string isEqualToString:@"."]) && textField.text.length == 0) {
        textField.text = @"0.";
        return NO;
    }
    
    if ([string isEqualToString:@"."] && [textField.text containsString:@"."])return NO;
    
    if ([textField.text containsString:@"."] && [toBeString componentsSeparatedByString:@"."].count > 1 && [toBeString componentsSeparatedByString:@"."].lastObject.length > 2) {
        return NO;
    }
    //设置为自己需要的位数(这里11位)
    if ([toBeString containsString:@"."] ? toBeString.length > 10+3 : toBeString.length > 10) {
        textField.text = [toBeString substringToIndex:[toBeString containsString:@"."] ?14:11];
        return NO;
    }
return YES; }

转载于:https://www.cnblogs.com/BagBear/p/9082950.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值