在我使用Swift 3的第一个应用程序中,用户可以在个人资料屏幕上输入他的出生日期。
用户点击文本字段,点击UI后显示DatePicker。我的问题是日期选择器只显示日期和时间。我希望有一个日历,用户可以选择他的出生日期,然后出生日期显示在文本字段中,稍后将保存在数据库中。我在这里遇到了很多答案,但它们主要基于日期选择器而不是日历。
override func viewDidLoad() {
super.viewDidLoad()
userDateofBirthTextField.delegate = self
}
func datePickerChanged(sender: UIDatePicker) {
let datePicker = UIDatePicker( )
datePicker.datePickerMode = UIDatePickerMode.date
datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
userDateofBirthTextField.inputView = datePicker // selected date should show in text field
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePicker = UIDatePicker()
textField.inputView = datePicker
datePicker.addTarget(self, action: #selector(datePickerChanged(sender:)), for: .valueChanged)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
userDateofBirthTextField.resignFirstResponder()
return true
}
func closekeyboard() {
self.view.endEditing(true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
closekeyboard()
}
答案 0 :(得分:0)
您可以更改如下。
在ViewDidLoad
中let datePicker = UIDatePicker()
datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
userDateofBirthTextField.addTarget(self, action: #selector(datePickerChanged(sender:)), for: .valueChanged)
textField.inputView = datePicker
选择方法
func datePickerChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy mm dd"
userDateofBirthTextField.text = formatter.string(from: sender.date)
}