UITextField限制输入个数和类型

swift方法

限制输入个数和只能输入的内容

  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var maxNum = 11
        if textField == newPhoneNumber {
            maxNum = 11
        }else if textField == iconCode{
            maxNum = 4
        }else if textField == smsCode{
            maxNum = 6
        }
        if textField == iconCode {
//            只允许的字符集
            let charact = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789").inverted
//            返回一个数组,从给定字符串中除去给定字符集的子字符串
            let array = string.components(separatedBy: charact)
//            返回一个新的字符串,通过在序列元素之间加入给定的字符
            let filerString = array.joined(separator: "")
          return  filerString == string
        }
//        限制个数
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        return updatedText.count <= maxNum
        
    }

oc方法

限制输入内容

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.XSPaasswordTF || textField == self.XSPasswordAgain) {
        NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    return YES;
}

限制个数

因为这个协议只有在将要变化前执行,不是变化后执行,否则打印的值和没有最新输入的字符

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSMutableString * XSString = [NSMutableString stringWithString:textField.text];
    [XSString replaceCharactersInRange:range withString:string];
    if (XSString.length>15) {
        textField.text = [XSString  substringToIndex:15];
        return NO;
    }
    return YES;
}

你可能感兴趣的:(UITextField限制输入个数和类型)