代码之家  ›  专栏  ›  技术社区  ›  KhanShaheb

在文本字段中键入时在文本字段字符之间添加连字符

  •  0
  • KhanShaheb  · 技术社区  · 6 年前

    我有一个最大字符范围为7的textfield,在3个字符之后,我想添加减号字符,然后像这个示例555-5555那样编写其余的字符。这是我的代码,但这是无效的,我怎么能修复这个?

    // MARK: -UITextField Action
    
        @objc func textFieldDidChanged(_ textField:UITextField ){
            //print(PlaceTextField.text!)
            if(textField.text?.count == 4){
                    if(textField.text?.contains("-"))!{
                        textField.text!.removeLast()
                        textField.text!.removeLast()
                    }
                }
                if(textField.text?.count == 3){
                    print("-\n")
                   textField.text = textField.text! + "-"
                }
        }
    

    我试着从 Here

    2 回复  |  直到 6 年前
        1
  •  1
  •   Rakesha Shastri    6 年前

    如果不将粘贴文本复制到文本字段中,则此操作应该有效。

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let text = textField.text, let textRange = Range(range, in: text) {
            let updatedText = text.replacingCharacters(in: textRange, with: string)
            if textField.text?.count == 3 && updatedText.count == 4 {
                textField.text = textField.text! + "-" + string
                return false
            }
            if textField.text?.count == 5 && updatedText.count == 4 {
                let text = textField.text!
                textField.text = String(text.prefix(3))
                return false
            }
        }
        return true
    }
    

    你的文本区键盘应该是数字键盘。

    yourTextField.keyboardType = .numberPad
    
        2
  •  0
  •   Ildar.Z    6 年前

    你可以用我的方法 gist . 它允许你创建自己的模式电话号码或其他任何东西,只是使用。希望有帮助!