Notification texts go here Contact Us Buy Now!

Entering Date in dd-MM-yyyy format using numeric keyboard in UITextField

We need to set a delegate for the text field to listen for changes in the text. This is done by setting the delegate property of the text field to self, which means that the view controller will be notified of any changes to the text field.


// in viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    // set delegate for your textfield
    txtDOB.delegate = self
}

The text field delegate method shouldChangeCharactersIn is called whenever the text in the text field is changed. This method takes three parameters:

  • textField: The text field that is being edited.
  • range: The range of characters that are being changed.
  • string: The new string that is being inserted into the text field.

In the shouldChangeCharactersIn method, we can check the length of the text in the text field and add a hyphen after every two characters. We can also check if the length of the text exceeds 10 characters and prevent the user from entering more characters.


// in textfield delegate method
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // check if the text field is the DOB text field
    if textField == txtDOB {
        // check the length of the text in the text field
        if txtDOB.text!.count == 2 || txtDOB.text!.count == 5 {
            // add a hyphen after every two characters
            txtDOB.text = txtDOB.text! + "-"
        }
        // check if the length of the text exceeds 10 characters
        return txtDOB.text!.count <= 10
    }
    // if the text field is not the DOB text field, allow the user to enter any character
    return true
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.