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.
Asked
Active
Viewed 1.0k times
4
-
I will suggest, create a Date picker which displays date in your desired format and put that picker view as a Input-view of that textfield. – Wolverine Feb 13 '17 at 09:47
-
I didn't tried anything till now, I have no clue how to implement – Haroon Feb 13 '17 at 09:47
-
Design requirement is to implement that with a keyboard not a picker, Date picker is already working – Haroon Feb 13 '17 at 09:48
-
down voter please provide comment. – Haroon Feb 13 '17 at 10:04
2 Answers
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