代码之家  ›  专栏  ›  技术社区  ›  Mukesh Gami

如何在ios中结合密码点和普通文本生成UITextField

  •  -1
  • Mukesh Gami  · 技术社区  · 7 年前

    目前,我的文本字段在UITextField中输入为“111-11-1111”。要求输入“-1111”。这是否可以通过将安全文本输入和普通文本相结合或通过任何其他方式来实现。

    2 回复  |  直到 7 年前
        1
  •  2
  •   rmaddy    7 年前

    您必须使用以下方法检查文本字段中的每个文本条目

    - (BOOL)textField:(UITextField *)textField
        shouldChangeCharactersInRange:(NSRange)range
                    replacementString:(NSString *)string
    

    此方法。在输入特定数量的条目后,您就可以在密码中添加-了。

        2
  •  1
  •   Rahul Dasgupta    7 年前

    您可以这样实现它。

    将变量声明为textCount

     var textCount = 0
     var originalString = String()
    

    然后重写函数func textField(\utextfield:UITextField,shouldChangeCharactersIn-range,replacementString-string-string)->Bool如下:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if string == "" {
            textCount = textCount - 1
    
            var truncated = textField.text?.substring(to: (textField.text?.index(before: (textField.text?.endIndex)!))!)
            textField.text = truncated
            if textCount == 5 || textCount == 3 {
                let truncated = textField.text?.substring(to: (textField.text?.index(before: (textField.text?.endIndex)!))!)
                textField.text = truncated
            }
            truncated = originalString.substring(to: originalString.index(before: originalString.endIndex))
            originalString = truncated!
    
        }
        else if textCount < 9 {
            if textCount == 3 || textCount == 5 {
                textField.text = textField.text! + "-"
            }
    
            if textCount <= 4 {
                textField.text = textField.text! + "*"
                originalString.append(string)
            }
            else {
                textField.text = textField.text! + string
                originalString.append(string)
            }
    
            textCount = textCount + 1
        }
        print(originalString)
    
        return false
    }
    

    记住将textfield的文本存储在委托本身中。否则它会给你错误的值。