If I have a UIDatePicker, and I wish to set the minimum and maximum date range to be between thirty years ago and thirty years in the future, how would I set that up?
Was looking at this issue today and came up with a solution in Swift 3 that extends UIDatePicker.
extension UIDatePicker
{
/// set the date picker values and set min/max
/// - parameter date: Date to set the picker to
/// - parameter unit: (years, days, months, hours, minutes...)
/// - parameter deltaMinimum: minimum date delta in units
/// - parameter deltaMaximum: maximum date delta in units
/// - parameter animated: Whether or not to use animation for setting picker
func setDate(_ date:Date, unit:NSCalendar.Unit, deltaMinimum:Int, deltaMaximum:Int, animated:Bool)
{
setDate(date, animated: animated)
setMinMax(unit: unit, deltaMinimum: deltaMinimum, deltaMaximum: deltaMaximum)
}
/// set the min/max for the date picker (uses the pickers current date)
/// - parameter unit: (years, days, months, hours, minutes...)
/// - parameter deltaMinimum: minimum date delta in units
/// - parameter deltaMaximum: maximum date delta in units
func setMinMax(unit:NSCalendar.Unit, deltaMinimum:Int, deltaMaximum:Int)
{
if let gregorian = NSCalendar(calendarIdentifier:.gregorian)
{
if let minDate = gregorian.date(byAdding: unit, value: deltaMinimum, to: self.date)
{
minimumDate = minDate
}
if let maxDate = gregorian.date(byAdding: unit, value: deltaMaximum, to: self.date)
{
maximumDate = maxDate
}
}
}
}
The setDate method will set three values (date, minimum, maximum) of the UIDatePicker instance.
setMinMax only sets the minimum and maximum. Minimum and maximum are calculated using the picker's current date.
Unit can be the following values:
To set the date with plus and minus thirty years, the code would be:
var datePicker = UIDatePicker()
var date = Date()
datePicker.setDate(date, unit:.year, deltaMinimum:-30, deltaMaximum:30, animated:true)