Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Created July 19, 2017 04:12
Show Gist options
  • Save anirudhamahale/eea0abbe9fafd687f2efa1d1bb6f7ab0 to your computer and use it in GitHub Desktop.
Save anirudhamahale/eea0abbe9fafd687f2efa1d1bb6f7ab0 to your computer and use it in GitHub Desktop.
Inserting Date Picker in UITextField
func insertDatePicker() {
let inputView = UIView(frame: CGRect(x: 0,y: 0, width: self.view.frame.width, height: 240))
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 240))
datePicker.datePickerMode = .date
let now: Date = Date()
var plusOneDay: DateComponents = DateComponents()
plusOneDay.day = +1
let oneDayAfter: Date = (Calendar.current as NSCalendar).date(byAdding: plusOneDay, to: now, options: NSCalendar.Options.init(rawValue: 0))!
datePicker.minimumDate = oneDayAfter
inputView.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(handleDatePicker(_:)), for: .valueChanged)
handleDatePicker(datePicker)
dateTextField.inputView = inputView
}
func handleDatePicker(_ sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
dateTextField.text = formatter.string(from: sender.date)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
insertDatePicker()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment