Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
YichenBman Avatar asked Mar 05 '15 00:03

YichenBman


2 Answers

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)
    }
}
like image 76
Leo Dabus Avatar answered Nov 17 '22 16:11

Leo Dabus


Swift 3 version of @Leo Dabus answer:

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

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

extension Date {
    var formatted: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return  formatter.string(from: self as Date)
    }
}
like image 3
Marcos Reboucas Avatar answered Nov 17 '22 18:11

Marcos Reboucas