YichenBman YichenBman - 3 months ago 31
iOS Question

swift not updating textfield.text using UIDatePicker

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

Xcode 7.3.1 • Swift 2.2.1

func handleDatePicker(sender: UIDatePicker) {
    textField3.text = datePicker.date.formatted
}

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



extension NSDate {
    var formatted: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return  formatter.stringFromDate(self)
    }
}