Set current date from datepicker on textfield

2019-07-29 22:19发布

问题:

I'm setting a datepicker on a textfield. For that this is what I've written..(in viewDidLoad)

    let datePicker = UIDatePicker()
    datePicker.datePickerMode = UIDatePickerMode.date
    datePicker.addTarget(self, action: #selector(AddDetailsViewController.theDatePickerValueChanged(sender:)), for: .valueChanged)
    dateTimeTextfield.inputView = datePicker

And outside viewDidLoad I have the function theDatePickerValueChanged given like so...

@objc func theDatePickerValueChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    dateTimeTextfield.text = formatter.string(from: sender.date)
}

But now what happens is when I tap on the textfield, the datePicker comes up. But if I want the current date to be set on the textfield, then I have to move forward or backward from the current date on the datePicker and then again return to that current date.

But what I want is when the datePicker comes up, the current date on it should be directly set on the textfield without me requiring to go forward or backwards from the current date. How can I achieve this...?

回答1:

You can implement text field delegate method textFieldShouldBeginEditing: and in that delegate method you need to do like this...

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {

  if dateTimeTextfield.text!.isEmpty {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    dateTimeTextfield.text = formatter.string(from: Date())
  }
  return true
}

Don't forgot to set dateTimeTextfield.delegate = self.



回答2:

Set UITextFieldDelegate and use textFieldDidBeginEditing.

//Set delegate
dateTimeTextfield.delegate = self


// UITextFieldDelegate method
func textFieldDidBeginEditing(_ textField: UITextField) -> void {

  if textField.text == nil || textField.text!.isEmpty {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    textField.text = formatter.string(from: Date())
  }

}


回答3:

Implement UITextFieldDelegate method textFieldShouldBeginEditing and call your function theDatePickerValueChanged like below:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {

    if dateTimeTextfield.text!.isEmpty {
        theDatePickerValueChanged(sender: UIDatePicker())
    }
    return true
}

Set dateTimeTextfield.delegate = self in viewDidLoad