Date & Time picker View
Some times we need to pick date or time in application for this we have to create the separate UIView and add UIDatePicker then perform functionality on it. swift provide default feature in UITextField where we need to add view as UIDatepicker so when we tap on it , this will show the respective data whatever you have set on UIDatepicker mode.
There is Various mode of UIDatePicker
a: date picker , time picker, date & Time picker.
For doing this , you have to follow this steps.
1: take a UITextfield in UIViewcontroller and create their outlet like
@IBOutlet weak var sampleDateTextField: UITextField!
2: Now Create the outlet as ActionMode and set editing method as didbeginedit ( this will work when you just tap on UItextfield)
like as
@IBAction func specialDateTextFieldClick(_ sender: UITextField) {}
3: Now define the method
1 2 3 4 5 6 7 |
@IBAction func specialDateTextFieldClick(_ sender: UIFloatLabelTextField) { let datePickerView:UIDatePicker = UIDatePicker() datePickerView.datePickerMode = UIDatePickerMode.date specialPriceFromTextField.inputView = datePickerView datePickerView.addTarget(self, action: #selector(ProductAttributeField.datePickerFromValueChanged), for: UIControlEvents.valueChanged) } |
4: Here I have set action , it will call this static method ”
1 |
ProductAttributeField.datePickerFromValueChanged |
”
Here “ProductAttributeField” is class and name of method is “datePickerFromValueChanged“
Note: you can set date picker mode according to your requirement.
5: Now it time to define their method like that.
1 2 3 4 5 6 |
func datePickerFromValueChanged(sender:UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" specialDateTextField.text = dateFormatter.string(from: sender.date) } |
Here I have set formatter ,it is required to display the date or you can set different formatter .
6: Now you tap on UITextField then datepicker will show and on changing then automatic fill the date on UItextField.