UIDatePicker, setting maximum and minimum dates based on todays date

前端 未结 7 1428
粉色の甜心
粉色の甜心 2020-12-02 18:36

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?

7条回答
  •  醉话见心
    2020-12-02 18:56

    Please Try this code Ios8+

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:30];
    NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [comps setYear:-30];
    NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    
    [datePicker setMaximumDate:maxDate];
    [datePicker setMinimumDate:minDate];
    

提交回复
热议问题