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

Adding hyphen between textfield character when typing in text filed

我有一个最大字符范围为 7 的文本字段,在 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! + "-"
            }
    }

我尝试从 解决,但无法正常工作。

您可以使用我的方法gist。它允许您为 phone 号码或其他任何东西创建自己的模式并使用。希望对您有所帮助!

如果您不将粘贴文本复制到文本字段,这应该有效。

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
}

P.S - 您的文本字段键盘应该是数字键盘。

yourTextField.keyboardType = .numberPad