MohanSingh MohanSingh - 2 months ago 36
Swift Question

Date picker does not open first click on textfield in swift 2.2

I have

datePicker
view that does not open at first time click on textField. If I click it second time then the date picker view is opened. I'm confused in this case. Why it did not open at first click? How to show date picker view in first click on
UITextField
?

Code I have try:

@IBAction func datePick(sender: UITextField)
{
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(SendSMS.showDatePicker), forControlEvents: UIControlEvents.ValueChanged)
}

func showDatePicker(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "HH:mm:SS"
timeField.text = timeFormatter.stringFromDate(sender.date)
dateField.text = dateFormatter.stringFromDate(sender.date)
}


Output:

enter image description here

Answer

Instead of setting action with textField try to use delegate method of UITextFieldDelegate.

func textFieldDidBeginEditing(textField: UITextField!) {    //delegate method
    if textField == dateField {
        let datePickerView = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Date
        textField.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(SendSMS.showDatePicker), forControlEvents: UIControlEvents.ValueChanged)
    }
}