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?
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)
}
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With