I need to add a "done" button to my date picker like in this image:
This is my code:
-(IBAction)chooseDate:(id)sender{
self.datepicker= [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)];
self.datepicker.datePickerMode = UIDatePickerModeDate;
datepicker.backgroundColor = Rgb2UIColor(52, 170, 220);
[self.btnDone
addTarget:self
action:@selector(SetDatePickerTime:)
forControlEvents:UIControlEventTouchDown];
[self.view addSubview:self.datepicker];
}
datePickerMode = UIDatePickerMode. Date inputView. addSubview(datePickerView) // add date picker to UIView let doneButton = UIButton(frame: CGRectMake((self. view.
Overview. You can use a date picker to allow a user to enter either a point in time (calendar date, time value, or both) or a time interval (for example, for a timer). The date picker reports interactions to its associated target object. To add a date picker to your interface: Set the date picker mode at creation time.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With