4

I use Swift to develop a iOS app. I have a text field on storyboard and need to set UIDatePicker as its input view. The following is my code.

@IBOutlet var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    var datePicker: UIDatePicker = UIDatePicker()
    datePicker.datePickerMode = UIDatePickerMode.CountDownTimer
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "HH:mm"
    datePicker.setDate(dateFormatter.dateFromString("01:00")!, animated: false)
    datePicker.addTarget(self, action: "datePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
    textField.inputView = datePicker
}

func datePickerValueChanged(sender: UIDatePicker) {
    println("Event is triggered.")
}

When I run the app and change value for the first time, ValueChanged event isn't triggered. When I change value for the second time, the event is triggered.

If I comment code datePicker.datePickerMode = UIDatePickerMode.CountDownTimer, the event will be triggered when value is changed for the first time.

I need to customize UIDatePickerMode to CountDownTimer. I also need to make sure the event is triggered when value is changed for the first time. How can I fix this issue?

Thank you.

user4708651
  • 55
  • 1
  • 6

1 Answers1

2

This may be a bug with the UIDatePicker in CountDownTimer mode (it may not be setting a default value for it to recognize the "change", not 100% sure though).

To get around this you can do the following in your viewDidLoad method:

 dispatch_async(dispatch_get_main_queue(), ^{
      datePicker.countDownDuration = (NSTimeInterval) duration;
 });
chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • Thank you for your reply. After I set default value, this problem still exists. I just updated code, which sets default value, in the question. – user4708651 Mar 24 '15 at 18:38
  • Check the update. This method might work better for you. I am unable to test as I am not near my mac sorry about that. – chrissukhram Mar 24 '15 at 20:09