Search code examples
swiftuitextfielduitextfielddelegate

Swift format text field when user is typing


I'm trying to format an expiry field so that it formats the text as follows: MM / YY I can get the textfield to add in the extra characters when the user is typing however when I come to delete the numbers the code will not allow you to go passed two characters before adding in the " / " again. Is there a way I can recognise when the user is deleting and bypass the text field check?

ExpiryOutlet.addTarget(self, action: #selector(ExpiryDidChange(_:)), for: .editingChanged)

func ExpiryDidChange(_ textField: UITextField) {
    if textField == ExpiryOutlet {

        if textField.text != "" && textField.text?.characters.count == 2 {
            textField.text = "\(textField.text!) / "
        }

    }
}

Thanks


Solution

  • Is there a way I can recognise when the user is deleting and bypass the text field check?

    The problem is that you've implemented the wrong method. Implement the delegate method text​Field(_:​should​Change​Characters​In:​replacement​String:​). This allows you distinguish where the text is changing (the second parameter is the range), and what the new text is — in the case of the backspace, replacementString will be empty.