Swift 3 | Xcode 8 datePicker update UItextField

13,225

The issue is with the selector syntax, from Swift 3 you need to specify the first parameter name inside selector, so change your selector syntax like this.

datePicker.addTarget(self, action: #selector(datePickerChanged(sender:)), for: .valueChanged)
Share:
13,225
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    This code allows you to update a textField using datePicker for Xcode 7 but when I try to implement it in Xcode 8 and Swift 3, the app crashes and throws a SIGABRT error in the AppDelegate.swift file. I've check all of my @IBs and I don't have any miscellaneous connections that need to be deleted. Any guidance would be greatly appreciated.

    import UIKit
    
    class ViewController: UIViewController, UITextFieldDelegate {
        @IBOutlet var eventStartText: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            eventStartText.delegate = self
    
            // Do any additional setup after loading the view.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        // MARK: TextField Delegate
        func datePickerChanged(sender: UIDatePicker) {
            let formatter = DateFormatter()
            formatter.dateStyle = .full
            eventStartText.text = formatter.string(from: sender.date)
    
            print("Try this at home")
        }
    
        func textFieldDidBeginEditing(_ textField: UITextField) {
            let datePicker = UIDatePicker()
            textField.inputView = datePicker
            datePicker.addTarget(self, action: (Selector(("datePickerChanged:"))), for: .valueChanged)
    
            print("This Worked")
        }
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            eventStartText.resignFirstResponder()
            return true
        }
    
        // MARK: Helper Methods
        func closekeyboard() {
            self.view.endEditing(true)
        }
    
        // MARK: Touch Events
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            closekeyboard()
        }
    
        /*
         // MARK: - Navigation
    
         // In a storyboard-based application, you will often want to do a little preparation before navigation
         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         // Get the new view controller using segue.destinationViewController.
         // Pass the selected object to the new view controller.
         }
         */
    }