UIDatePicker with "done" button
With Swift
// Place this code inside your ViewController or where you want ;)
var txtField: UITextField = UITextField(frame: CGRectMake(0, 0, 200, 50))
// the formatter should be "compliant" to the UIDatePickerMode selected below
var dateFormatter: NSDateFormatter {
let formatter = NSDateFormatter()
// customize the locale for the formatter if you want
//formatter.locale = NSLocale(localeIdentifier: "it_IT")
formatter.dateFormat = "dd/MM/yyyy"
return formatter
}
override func viewDidLoad() {
super.viewDidLoad()
// date picker setup
let datePickerView:UIDatePicker = UIDatePicker()
// choose the mode you want
// other options are: DateAndTime, Time, CountDownTimer
datePickerView.datePickerMode = UIDatePickerMode.Date
// choose your locale or leave the default (system)
//datePickerView.locale = NSLocale.init(localeIdentifier: "it_IT")
datePickerView.addTarget(self, action: "onDatePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
txtField.inputView = datePickerView
// datepicker toolbar setup
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "doneDatePickerPressed")
// if you remove the space element, the "done" button will be left aligned
// you can add more items if you want
toolBar.setItems([space, doneButton], animated: false)
toolBar.userInteractionEnabled = true
toolBar.sizeToFit()
txtField.inputAccessoryView = toolBar
self.view.addSubview(txtField)
}
func doneDatePickerPressed(){
self.view.endEditing(true)
}
func onDatePickerValueChanged(datePicker: UIDatePicker) {
self.txtField = dateFormatter.stringFromDate(datePicker.date)
}
Create a date picker, then add it as the input view of the field in question (self.fieldInQuestion.inputView = datePicker
). Next, create a UIToolBar
(height 44) with UIBarButton
Item on it with the title "Done", target of self, and a selector (ex. @selector(done)). Add this as the input accessory view of the same field you made the date picker an input view for (self.fieldInQuestion.inputAccessoryView = UIToolbarInstance
). In the selector method (-(void)done in the example above), make sure you use [self.fieldInQuestion resignFirstResponder] and it will dismiss it.