here is my code.
extension ProfileViewController {
private func openDatePicker() {
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
ageTextFieldOutlet.inputView = datePicker
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))
let cancleButton = UIBarButtonItem(title: "Cancle", style: .plain, target: self, action: #selector(cancleButtonClicked))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonClicked))
let flexibleBtn = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([cancleButton, flexibleBtn, doneButton], animated: true)
ageTextFieldOutlet.inputAccessoryView = toolBar
}
@objc func cancleButtonClicked() {
ageTextFieldOutlet.resignFirstResponder()
}
@objc func doneButtonClicked() {
if let datePiker = ageTextFieldOutlet.inputView as? UIDatePicker {
print(datePiker.date)
}
}
}
// MARK: - UITextFieldDelegate For Age
extension ProfileViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
self.openDatePicker()
}
}
And Image For Better Understanding.
In newer versions of iOS (13.4+) you need to specify a style if you want the wheel date picker, by default it is automatic, and it usually defaults to compact, in this case when you create a new UIDatePicker you can do this:
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
datePicker.preferredDatePickerStyle = .wheels
ageTextFieldOutlet.inputView = datePicker