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
}