0

I'm a newbie to swift. I'm using xcode version 8 beta 4. I'm having an error whenever I scroll through my Date Picker. I have read a very similar problem, but the answer there is not fixing my problem. Below is my code:

func textFieldDidBeginEditing(_ textField: UITextField) {
    let datePicker = UIDatePicker()
    textField.inputView = datePicker
    datePicker.addTarget(self, action: Selector("datePickerChanged:"), for: .valueChanged)        
}

func datePickerChanged(sender: UIDatePicker){
    let formatter = DateFormatter()
    formatter.dateStyle = .long
    dateLog.text = formatter.string(from: sender.date)
}

when I click on my textfield the UIDatePicker is showing up just fine, but when I start to scroll through the dates, it gives me the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyApp.ViewController datePickerChanged:]: unrecognized selector sent to instance 0x7f90f1f04180'

Community
  • 1
  • 1
iceman
  • 7
  • 1
  • 2
  • 5

2 Answers2

4

Selector(String) is deprecated. You should start using the new syntax #selector.

Also, the colon at the end is not needed.

So, your code should look like this:

datePicker.addTarget(self, action: #selector(datePickerChanged), 
    for: .valueChanged)
Xcoder
  • 1,433
  • 3
  • 17
  • 37
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • @vadian I know. I tried OPs's code and it didn't crash. But nonetheless, the non-deprecated syntax should always be used imo. – Sweeper Sep 04 '16 at 14:58
  • Thanks! It worked! I also did it this way and it also worked: `datePicker.addTarget(self, action: #selector(datePickerChanged(_:)), for: .valueChanged)` but i had to change my datePickerChanged function too: `func datePickerChanged(_ sender: UIDatePicker)` – iceman Sep 06 '16 at 12:27
-1
  1. change the Selector to #selector
  2. change for to forControlEvents
  3. change .valueChanged to .ValueChanged

    datePicker.addTarget(self, action: #selector(yourClass.datePickerChanged), forControlEvents: .ValueChanged) 
    
hariszaman
  • 8,202
  • 2
  • 40
  • 59