I followed this thread: datepicker by clicking on textfield
I imported both of the following protocols:
@interface ViewController : UIViewController&
A nice approach is to make your own class (I called it TextFieldFormDate
) that is derived from UITextField
and encapsulates all the required behaviour. In your storyboard you then set the class for the text field to TextFieldFormDate
(in my case).
Use didChange
and didSelect
in your ViewController (that is using the TextFieldFormDate
) to be notified of changes and when date is actually picked.
class TextFieldFormDate: UITextField {
var date : Date {
set {
picker.date = newValue
text = newValue.localizedDateOnly()
}
get {
return picker.date
}
}
//public handlers
var didChange : ( (Date)->() )?
var didSelect : ( (Date)->() )?
private var picker : UIDatePicker {
return inputView as! UIDatePicker
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
font = UIFont.defaultFont()
//picker for datefield
inputView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
picker.datePickerMode = .date
picker.addTarget(self, action: #selector(pickerChanged), for: .valueChanged)
let toolBar = UIToolbar()
toolBar.tintColor = PaintCode.mainBlue
toolBar.items = [
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
BarBtnPaintCode(type: "done", target: self, action: #selector(didPressDone))
]
toolBar.sizeToFit()
inputAccessoryView = toolBar
}
@objc private func pickerChanged() {
text = date.localizedDateOnly()
didChange?(picker.date)
}
@objc private func didPressDone() {
text = date.localizedDateOnly()
resignFirstResponder()
didSelect?(picker.date)
}
}