Kunj Patel Kunj Patel - 3 years ago 237
iOS Question

UIDatePicker date constrains Swift 3

I am using UIDatePicker view to let the users set the date for my app. Currently, the date picker shows previous dates as well, meaning, the dates past "Today"'s date. Previous dates from the current date are irrelevant for my app. How do i set this kind of constrains in my code in order to achieve this functionality? I tried searching for this specific problem but no luck so far.
I read about minimum date and maximum date but i don't know how to go about implementing that. Any sample code would be appreciated

Here's what i have so far:

@IBAction func dateTimePicker(_ sender: UITextField) {

let datePicker = UIDatePicker()

datePicker.datePickerMode = .dateAndTime

sender.inputView = datePicker

datePicker.addTarget(self, action: #selector(AddEventsViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)


func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.short
txtTimeDate.text = dateFormatter.string(from: sender.date) //puts the date in tetxfield

Answer Source

Read the UIDatePicker documentation:

To limit the range of dates that the user can select, assign values to the minimumDate and maximumDate properties. You can also use the minuteInterval property to allow only specific time increments.


datePicker.minimumDate = Date()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download