4

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

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Haroon
  • 697
  • 1
  • 9
  • 24

2 Answers2

16

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;

}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • Thanks Anbu.Karthik, Its working as per requirement, one minor question if you can help. I want only numeric characters, number keyboard have decimal point too. how can I avoid that ? – Haroon Feb 13 '17 at 10:03
  • @Haroon - see this http://stackoverflow.com/questions/30973044/how-to-restrict-uitextfield-to-take-only-numbers-in-swift – Anbu.Karthik Feb 13 '17 at 10:07
4

Updated for Swift 5

if textField == dateTextField {
            if dateTextField.text?.count == 2 || dateTextField.text?.count == 5 {
                //Handle backspace being pressed
                if !(string == "") {
                    // append the text
                    dateTextField.text = dateTextField.text! + "."
                }
            }
            // check the condition not exceed 9 chars
            return !(textField.text!.count > 9 && (string.count ) > range.length)
        } else {
            return true
        }
Ihor Chernysh
  • 446
  • 4
  • 5