美文网首页
iOS限制输入内容的类型、长度的解决办法

iOS限制输入内容的类型、长度的解决办法

作者: Summer_YJL | 来源:发表于2017-09-13 11:41 被阅读0次

    限制文字输入

      //数字
     #define NUM @"0123456789"
     //字母
     #define ALPHA      @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
     //数字和字母
     #define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    
    
    
    
    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([textField.placeholder isEqualToString:@"请输入银行卡号"]) {
        //
        NSString *text = [textField text];
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            return NO;
        }
        
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        if (newString.length > 24) {
            return NO;
        }
        [textField setText:newString];
        return NO;
        
    }else if ([textField.placeholder isEqualToString:@"请设置6位提现密码"]){
        //
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (range.location >= 6) { //
            return NO;
        }
        return [string isEqualToString:filtered];
        
    }else if ([textField.placeholder isEqualToString:@"请输入提现密码"]){
        //
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (range.location >= 6) { //
            return NO;
        }
        return [string isEqualToString:filtered];
        
    }else{
        
        return YES;
    }
    }

    相关文章

      网友评论

          本文标题:iOS限制输入内容的类型、长度的解决办法

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