iOS限制textfield输入两位小数
<pre name="code" class="objc">#define myDotNumbers     @"0123456789.\n"   //匹配金额
#define myNumbers          @"0123456789\n"  //匹配数字

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *cs;
    if ([textField isEqual:_accountMoney]) {
        NSScanner * scanner = [NSScanner scannerWithString:string];
        NSRange pointRange = [textField.text rangeOfString:@"."];
        if ((pointRange.length > 0 ) && (pointRange.location < range.location || pointRange.location > range.location + range.length)) {
            cs = [NSCharacterSet characterSetWithCharactersInString:myNumbers];
        }
        else {
            cs = [NSCharacterSet characterSetWithCharactersInString:myDotNumbers];
        }
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."]) {
            return NO;
        }
        short remain = 2;
        NSString * tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if (pointRange.length > 0 && pointRange.location > 0) {
            if ([string isEqualToString:@"."]) {
                return NO;
            }
            if (strlen > 0 && (strlen - pointRange.location) > remain + 1) {
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if (zeroRange.length == 1 && zeroRange.location == 0 ) {
            if (![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1) {
                textField.text = string;
                return NO;
            }
            else {
                if (pointRange.length == 0 && pointRange.location > 0 ) {
                    if ([string isEqualToString:@"0"]) {
                        return NO;
                    }
                }
            }
        }
        NSString * buffer;
        if (![scanner scanCharactersFromSet:cs intoString:&buffer] && ([string length] != 0 )) {
            return NO;
        }
    }
    return YES;
}




阅读更多
个人分类: oc基本知识点
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

iOS限制textfield输入两位小数

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭