swift not updating textfield.text using UIDatePicker

YichenBman picture YichenBman · Mar 5, 2015 · Viewed 8.6k times · Source

In swift, I have a textField programmatically declared.

override func viewDidLoad() {
    super.viewDidLoad()
textField3.delegate = self

    textField3.returnKeyType = UIReturnKeyType.Next;
    datePicker.datePickerMode = UIDatePickerMode.Date
    datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
    textField3.inputView = datePicker


}

 func handleDatePicker(sender: UIDatePicker) {

    textField3.text = dateFormatter.stringFromDate(sender.date)
            }

All the other questions I've found similar to this deal with interface builder, and haven't helped. How would i fix this programmatically?

Answer

Leo Dabus picture Leo Dabus · Mar 5, 2015

Xcode 9 • Swift 4

@objc func handleDatePicker(_ datePicker: UIDatePicker) {
    textField3.text = datePicker.date.formatted
}

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.addTarget(self, action: #selector(handleDatePicker), forControlEvents: .valueChanged)
}

extension Date {
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return formatter
    }()
    var formatted: String {
        return Date.formatter.string(from: self)
    }
}