I use the following code in swift 3 to bring up date picker.
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
formatter.dateStyle = .long
formatter.timeStyle = .none
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(sender:)), 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.
}
*/
}
How would i go about to only having day month and year. and since i am asked to supply more details then to make things clear, what i need is for swift 3 date picker to display day month year only Thanks
If you want to show only day, month and year with picker then simply set datePickerMode
property of UIDatePicker
to .date
let datePicker = UIDatePicker()
//set datePickerMode to date
datePicker.datePickerMode = .date
textField.inputView = datePicker
datePicker.addTarget(self, action: #selector(datePickerChanged(sender:)), for: .valueChanged)