Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 | Xcode 8 datePicker update UItextField

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.
     }
     */
}
like image 694
Tom Bednarczyk Avatar asked Sep 23 '16 15:09

Tom Bednarczyk


1 Answers

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)
like image 140
Nirav D Avatar answered Sep 24 '22 01:09

Nirav D