Search code examples
iosswiftuitextfielddate-formatting

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


I want to format (dd-MM-yyyy) the text while entering in UITextField. I am using Swift 3.0, Any suggestion how I can implement the same.


Solution

  • use like

    // create one textfield
    @IBOutlet var txtDOB: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        // set delegate for your textfield
        txtDOB.delegate = self
    
    }
    

    // call your function in textfield delegate shouldChangeCharactersIn

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //Format Date of Birth dd-MM-yyyy
    
        //initially identify your textfield
    
        if textField == txtDOB {
    
            // check the chars length dd -->2 at the same time calculate the dd-MM --> 5
            if (txtDOB?.text?.characters.count == 2) || (txtDOB?.text?.characters.count == 5) {
                //Handle backspace being pressed
                if !(string == "") {
                    // append the text
                    txtDOB?.text = (txtDOB?.text)! + "-"
                }
            }
            // check the condition not exceed 9 chars
            return !(textField.text!.characters.count > 9 && (string.characters.count ) > range.length)
        }
        else {
            return true
        }
    }
    

    ObjectiveC

      - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
      {
    //Format Date of Birth dd-MM-yyyy
    
     if(textField == txtDOB)
        {
        if ((txtDOB.text.length == 2)||(txtDOB.text.length == 5))
            //Handle backspace being pressed
            if (![string isEqualToString:@""])
                txtDOB.text = [txtDOB.text stringByAppendingString:@"-"];
        return !([textField.text length]>9 && [string length] > range.length);
    }
    else
        return YES;
    
    }