UIDatePicker as a Inputview to UITextField - ios

In my code i have used Datepicker as a Inputview to Textfield
self.tFPeriodEndCurrent.inputView = self.datePicker
textfield delegates won't work because Textfield is not editable.
i need to update text(date) in textfield to UIPicker input view when ever user clicked on Textfield
//assume textfield contains 20/2/2019 , that should reflect in UIdatepicker when user Tap on textfield.
how to acheive that! any help

Firstly create datePicker programmatically:
private lazy var datePicker: UIDatePicker = {
let datePicker = UIDatePicker(frame: .zero)
datePicker.datePickerMode = .date
datePicker.timeZone = TimeZone.current
return datePicker
}()
In 'viewDidLoad' or 'awakeFromNib':
fieldValueTextField.inputView = datePicker
datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
Create the method that will handle editing:
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
fieldValueTextField.text = dateFormatter.string(from: sender.date)
}
In Swift 5, Xcode 12 use the following:
if #available(iOS 14, *) {
datePicker.preferredDatePickerStyle = .wheels
}
It will set the picker to the same like in iOS 13.

If you want to bring the same UIPickerView look & feel try this,
class ViewController: UIViewController {
#IBOutlet weak var dateField: UITextField!
var datePicker :UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
datePicker = UIDatePicker.init(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 200))
datePicker.addTarget(self, action: #selector(self.dateChanged), for: .allEvents)
dateField.inputView = datePicker
let doneButton = UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(self.datePickerDone))
let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 44))
toolBar.setItems([UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil), doneButton], animated: true)
dateField.inputAccessoryView = toolBar
}
#objc func datePickerDone() {
dateField.resignFirstResponder()
}
#objc func dateChanged() {
dateField.text = "\(datePicker.date)"
}
}

class ViewController: UIViewController {
#IBOutlet weak var txtDatePicker: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
txtDatePicker.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}
#objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtDatePicker.text = dateFormatter.string(from: sender.date)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}

First you need to convert the string into date.
Assume textfield contains "20/2/2019"
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"dd/M/yyyy";
NSDate *dt = [formatter dateFromString:self.textField.text];
You also need to implement UITextFieldDelegate method
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (self.tFPeriodEndCurrent == textField) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"dd/M/yyyy";
NSDate *dt = [formatter dateFromString:textField.text];
if (textField.inputView isKindOfClass:[UIDatePicker class]) {
UIDatePicker *dtPicker = (UIDatePicker *)textField.inputView;
[dtPicker setDate:dt];
}
}
return TRUE;
}
Don't forget to set the textfield delegate.
Swift version
var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
return formatter
}()
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
guard let txtDate = textField.text else { return true }
if textField == tFPeriodEndCurrent, let dt = dateFormatter.date(from: txtDate) {
if let datePicker = textField.inputView as? UIDatePicker {
datePicker.setDate(dt, animated: true)
}
}
return true
}

Related

Textfield and datepicker change values

I try to use this code to get date picker when clicking on a text field:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var DOBTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed))
}
#objc func doneButtonPressed() {
if let datePicker = self.DOBTextField.inputView as? UIDatePicker {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.init(identifier: "it_IT")
self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
}
self.DOBTextField.resignFirstResponder()
}
}
extension UITextField {
func addInputViewDatePicker(target: Any, selector: Selector) {
let screenWidth = UIScreen.main.bounds.width
//Add DatePicker as inputView
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .time
datePicker.locale = Locale.init(identifier: "it_IT")
self.inputView = datePicker
//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func cancelPressed() {
self.resignFirstResponder()
}
}
But when I click on text field again, time on date picker move forward on 3 dimensions. How this can be fixed? I want time on date picker to rest the same as it is on text field.
I try to implement this code, but it crash:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var DOBTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text ?? "")
}
#objc func doneButtonPressed() {
if let datePicker = self.DOBTextField.inputView as? UIDatePicker {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.init(identifier: "it_IT")
self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
}
self.DOBTextField.resignFirstResponder()
}
}
extension UITextField {
func addInputViewDatePicker(target: Any, selector: Selector , textFieldText: String?) {
let screenWidth = UIScreen.main.bounds.width
//Add DatePicker as inputView
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .time
datePicker.locale = Locale.init(identifier: "it_IT")
self.inputView = datePicker
if textFieldText != nil {
/// Set Textfield date & time
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.init(identifier: "it_IT")
datePicker.date = dateFormatter.date(from: textFieldText!)!
}
else {
/// set current date & time
datePicker.date = Date()
}
//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func cancelPressed() {
self.resignFirstResponder()
}
}
How this can be fixed?
As per I understand, You want to textfield's time when datepicker opens. You just have to set date for DatePicker when it will be initialized.
Set DatePicker's date :
extension UITextField {
func addInputViewDatePicker(target: Any, selector: Selector , textFieldText:String?) {
//Add DatePicker as inputView
//Set date for date Picker
if textFieldText != nil {
/// Set Textfield date & time
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.init(identifier: "it_IT")
datePicker.date = dateFormatter.date(from: textFieldText!)!
}
else {
/// set current date & time
datePicker.date = Date()
}
//Add Tool Bar as input AccessoryView
}
}
Change in your viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text ?? "")
}
I hope you understand what you have to set with datepicker. If this code is not working as you want then take Action of textfield (Editing Did Begin) & try to set textfield inputView in Action.
It seems this problem only appears on simulators. When I try to test this code on real device everything works fine. May be it's just Xcode bug.

Cannot convert string to date for datePicker

I try to get string from textfield, then convert it to date and put this value in datepicker. But for some reason it fails everytime and I get: "There is issue in dateformatter. Not able to convert string to Date".
I don't understand what I'm doing wrong and how I get this works.
My code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var DOBTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text)
}
#objc func doneButtonPressed() {
if let datePicker = self.DOBTextField.inputView as? UIDatePicker {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
}
self.DOBTextField.resignFirstResponder()
}
}
extension UITextField {
func addInputViewDatePicker(target: Any, selector: Selector , textFieldText: String?) {
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .date
self.inputView = datePicker
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
if textFieldText != nil {
if let date = dateFormatter.date(from: textFieldText!) {
datePicker.date = date
} else {
print("There is issue in dateformatter. Not able to convert string to Date ")
}
}
else {
datePicker.date = Date()
}
//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func cancelPressed() {
self.resignFirstResponder()
}
}
I don't understand what I'm doing wrong and why this code doesn't work. May be someone can help me resolve this issue?
As I see when you call addInputViewDatePicker on viewDidLoad, the value of textFieldText is "" that's why you see your print from start
you can try use this code (but, I guess, you can optimize it):
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var DOBTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
prepareDOBTextField()
DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text)
}
#objc func doneButtonPressed() {
if let datePicker = self.DOBTextField.inputView as? UIDatePicker {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
}
self.DOBTextField.resignFirstResponder()
}
func prepareDOBTextField() {
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none
let result = formatter.string(from: date)
self.DOBTextField.text = result
}
}
extension UITextField {
func addInputViewDatePicker(target: Any, selector: Selector , textFieldText: String?) {
let screenWidth = UIScreen.main.bounds.width
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .date
self.inputView = datePicker
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
if textFieldText != nil && textFieldText != "" {
if let date = dateFormatter.date(from: textFieldText!) {
datePicker.date = date
} else {
print("There is issue in dateformatter. Not able to convert string to Date ")
}
}
else {
datePicker.date = Date()
}
//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)
self.inputAccessoryView = toolBar
}
#objc func cancelPressed() {
self.resignFirstResponder()
}
}
You can do this by follow my code below.
#objc func doneButtonPressed() {
//Converting string to date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let date = dateFormatter.date(from: DOBTextField.text!)
//Sets the date in the date picker
datepicker.setDate(date!, animated: true)
}
So first you're converting your textfield (DOBTextField.text) into Date.
Right after you're setting the datePicker to be the correct date.
In this case you will have to enter exactly like this in the textfield:
"2019-12-18 14:50"
Solved this question. I get rid of extenstion and write code for datepicker in ViewController.
import UIKit
class ViewController: UIViewController {
#IBOutlet var textField: UITextField!
let datePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
createDatePicker()
}
func createDatePicker() {
textField.inputView = datePicker
datePicker.datePickerMode = .date
datePicker.maximumDate = Date()
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.setItems([flexibleSpace, doneButton], animated: true)
textField.inputAccessoryView = toolbar
}
#objc func doneClicked() {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
textField.text = dateFormatter.string(from: datePicker.date)
self.view.endEditing(true)
}
}
After I added to viewWillAppear actual values of datepicker:
override func viewWillAppear(_ animated: Bool) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
datePicker.date = dateFormatter.date(from: textfield.text!)!
}

Using datePicker for multiple textfields in iOS swift

I am having 4 textFields where I have to set fromDate, fromTime and toDate, toTime for a userServiceBooking. Now, I need to fill these textFields with UIDatePicker and I am not able to show the text and I don't know why; maybe I am doing it totally wrong...
I am posting the code that I've tried and please someone look into it and tell how to do it.
Code:
import UIKit
class ConfirmRequestViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var fromDateTF: UITextField!
#IBOutlet weak var toDateTF: UITextField!
#IBOutlet weak var fromTimeTF: UITextField!
#IBOutlet weak var toTimeTF: UITextField!
var datePicker = UIDatePicker()
var dateFormatter = DateFormatter()
var toolBar = UIToolbar()
override func viewDidLoad() {
super.viewDidLoad()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == fromDateTF {
datePicker.datePickerMode = .date
fromDateTF.inputView = datePicker
fromDateTF.text = dateFormatter.string(from: datePicker.date)
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
toolBar.setItems([doneButton], animated: true)
fromDateTF.inputAccessoryView = toolBar
}
if textField == toDateTF {
datePicker.datePickerMode = .date
toDateTF.inputView = datePicker
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
toolBar.setItems([doneButton], animated: true)
toDateTF.inputAccessoryView = toolBar
}
if textField == fromTimeTF {
datePicker.datePickerMode = .time
fromTimeTF.inputView = datePicker
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
toolBar.setItems([doneButton], animated: true)
fromTimeTF.inputAccessoryView = toolBar
}
if textField == toTimeTF {
datePicker.datePickerMode = .time
toTimeTF.inputView = datePicker
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
toolBar.setItems([doneButton], animated: true)
toTimeTF.inputAccessoryView = toolBar
}
}
#objc func doneButtonTapped(textField: UITextField) {
if textField == fromDateTF {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
fromDateTF.text = dateFormatter.string(from: datePicker.date)
}
if textField == toDateTF {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
toDateTF.text = dateFormatter.string(from: datePicker.date)
}
if textField == fromTimeTF {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
fromTimeTF.text = dateFormatter.string(from: datePicker.date)
}
if textField == toTimeTF {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
toTimeTF.text = dateFormatter.string(from: datePicker.date)
}
self.view.endEditing(true)
}
}
Try this.
override func viewDidLoad() {
super.viewDidLoad()
fromDateTF.inputView = datePicker
toDateTF.inputView = datePicker
fromTimeTF.inputView = datePicker
toTimeTF.inputView = datePicker
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped))
toolBar.setItems([doneButton], animated: true)
fromDateTF.inputAccessoryView = toolBar
toDateTF.inputAccessoryView = toolBar
fromTimeTF.inputAccessoryView = toolBar
toTimeTF.inputAccessoryView = toolBar
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == fromDateTF {
datePicker.datePickerMode = .date
}
if textField == toDateTF {
datePicker.datePickerMode = .date
}
if textField == fromTimeTF {
datePicker.datePickerMode = .time
}
if textField == toTimeTF {
datePicker.datePickerMode = .time
}
}
#objc func doneButtonTapped() {
if fromDateTF.isFirstResponder {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
fromDateTF.text = dateFormatter.string(from: datePicker.date)
}
if toDateTF.isFirstResponder {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
toDateTF.text = dateFormatter.string(from: datePicker.date)
}
if fromTimeTF.isFirstResponder {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
fromTimeTF.text = dateFormatter.string(from: datePicker.date)
}
if toTimeTF.isFirstResponder {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .medium
toTimeTF.text = dateFormatter.string(from: datePicker.date)
}
self.view.endEditing(true)
}

cannot assign value of type UIDatePicker to type string? Swift 2.2

I have this error at line "AvailableDayTextField.text = datePicker"
#IBOutlet var AvailableDayTextField: UITextField!
let datePicker = UIDatePicker()
func createDatePicker(){
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done , target: nil , action: nil)
toolbar.setItems([doneButton], animated: false)
AvailableDayTextField.text = datePicker
}
do like
on your ViewDidLoad set like
datePicker.date = NSDate()
datePicker.datePickerMode = .Date
datePicker.addTarget(self, action: #selector(self.dateTextField), forControlEvents: .ValueChanged)
AvailableDayTextField.inputView = datePicker
and call the fucntion as
func dateTextField(sender: AnyObject) {
var picker = (AvailableDayTextField.inputView as! UIDatePicker)
picker.maximumDate = NSDate()
var dateFormat = NSDateFormatter()
var eventDate = picker.date
dateFormat.dateFormat = "dd/MM/yyyy"
var dateString = dateFormat.stringFromDate(eventDate)
AvailableDayTextField.text = "\(dateString)"
}

UIDatePicker on button tap

So far I've only found date-picker bound to UITextField, but I need a date-picker which opens on UIButton tap in the same way as it does with the UITextField.
Is it possible? And if so, how? Thanks in advance.
#IBAction func BtnClicked(sender: AnyObject) {
var picker : UIDatePicker = UIDatePicker()
picker.datePickerMode = UIDatePickerMode.Date
picker.addTarget(self, action: "dueDateChanged:", forControlEvents: UIControlEvents.ValueChanged)
var pickerSize : CGSize = picker.sizeThatFits(CGSizeZero)
picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460)
// you probably don't want to set background color as black
// picker.backgroundColor = UIColor.blackColor()
self.view.addSubview(picker)
}
func dueDateChanged(sender:UIDatePicker){
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
self.myLabel.text = dateFormatter.stringFromDate(dueDatePickerView.date)
}
because i dont have enough reputation to comment , i am posting same answer of #iAnurag in Swift 4
#IBAction func UpdateDOBClick(_ sender: UIButton) {
let picker : UIDatePicker = UIDatePicker()
picker.datePickerMode = UIDatePickerMode.date
picker.addTarget(self, action: #selector(dueDateChanged(sender:)), for: UIControlEvents.valueChanged)
let pickerSize : CGSize = picker.sizeThatFits(CGSize.zero)
picker.frame = CGRect(x:0.0, y:250, width:pickerSize.width, height:460)
// you probably don't want to set background color as black
// picker.backgroundColor = UIColor.blackColor()
self.view.addSubview(picker)
}
#objc func dueDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dobButton.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
Here is another approach using .hidden feature of the controls. I use a button that changes the title when touched and hides/shows the date picker.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var showDate: UILabel!
#IBOutlet weak var myButtonx: UIButton!
#IBAction func myButton(sender: UIButton) {
if myButtonx.titleLabel?.text != "Done" {
// save the date for your need
showDate.text = "\(myDatePicker.date)"
myDatePicker.hidden = false
myButtonx.setTitle("Done",forState: UIControlState.Normal)
} else {
myDatePicker.hidden = true
myButtonx.setTitle("Pick Date",forState: UIControlState.Normal)
}
}
#IBOutlet weak var myDatePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
myDatePicker.hidden = true
myButtonx.setTitle("Pick Date",forState: UIControlState.Normal)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
private var datePicker: UIDatePicker?
#IBAction func dateFilterAction(_ sender: UIButton) {
if self.view.subviews.contains(where: { $0 is UIDatePicker }) {
self.datePicker?.removeFromSuperview()
dateFilter.setTitle("Datum", for: .normal)
} else {
datePicker = nil
setupDatePicker()
}
}
private func setupDatePicker() {
let picker = datePicker ?? UIDatePicker()
picker.datePickerMode = .date
if #available(iOS 13.4, *) {
picker.preferredDatePickerStyle = .wheels
}
picker.addTarget(self, action: #selector(dueDateChanged(sender:)), for: .valueChanged)
let size = self.view.frame.size
picker.frame = CGRect(x: 0.0, y: size.height - 200, width: size.width, height: 200)
picker.backgroundColor = UIColor.white
self.datePicker = picker
self.view.addSubview(self.datePicker!)
}
#objc func dueDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
print("action")
dateFilter.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}

Resources