这是我的代码。
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()
}
}
和图像以便更好地理解。