当我选择应用停止响应的日期时。我想选择日期并在文本字段中显示它而不按完成按钮。所以我希望看到现场直播。
如何根据TextField上选定的日期选择器打印年龄?
import UIKit
import Firebase
class SignUpEmailSegue0: UIViewController {
@IBOutlet weak var dateBirthday: UITextField!
@IBAction func dateBirthdayEdit(_ sender: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
}
@objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MMM/yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
}
答案 0 :(得分:1)
尝试按以下方式更改代码 - 使用#selector()
并将您的功能展示给@objc
datePickerView.addTarget(self, action: #selector(handleDatePicker), for: UIControlEvents.valueChanged)
@objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateBirthday.text = dateFormatter.string(from: sender.date)
}
回答关于如何获得年龄的第二个问题:
let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: sender.date, to: Date())
if let age = ageComponents.year {
print(age)
}