Brian L
Brian L

Reputation: 601

text field with date picker crashes on date changed swift

I am having trouble with a text field that I am setting up. The goal is instead of the keyboard, I want it to have slide wheels to indicate a time. So inside viewDidLoad() I put:

let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.time
datePicker.addTarget(self, action: Selector("datePickerValueChanged"), for: UIControlEvents.valueChanged)
textField.inputView = datePicker

And within the ViewController() I put:

@objc func datePickerValueChanged(sender: UIDatePicker) {
    let DatePickerView: UIDatePicker = UIDatePicker()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm"
    textField.text = dateFormatter.string(from: DatePickerView.date)
}

Now this looks great for opening the text field, the scroll bars for time pop right up, and look great (Woot!). But when I change the time, the application crashes (NSException). I understand that this usually occurs when a connection is not properly set up, but I can not figure out what connection as the Selector for textField should trigger function datePickerValueChanged. The scene loads fine, it is just when I change the date that I get NSException.

I also tried with/without @objc function label

I found solutions to three other similar questions, but they did not seem to work for me (maybe outdated). Links:

UIDatePicker crashing application

Inputting DatePicker in TextField problems

UITextField with DatePicker crashes

Any thoughts/ideas would be much appreciated.

Upvotes: 1

Views: 1074

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236538

To fix the crash change your selector from

datePicker.addTarget(self, action: Selector("datePickerValueChanged"), for: UIControlEvents.valueChanged)

to

datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)

and in your method:

@objc func datePickerValueChanged(_ sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "hh:mm a" // or "HH:mm"
    textField.text = dateFormatter.string(from: sender.date)
}

Upvotes: 2

Related Questions