无法向DatePicker添加最大和最小日期

时间:2015-02-06 09:55:23

标签: ios uidatepicker

我正在尝试将最大值和最小值设置为我的日期选择器但是它没有正确设置此属性。

我这样做如下:

    - (void)viewDidLoad {
    [super viewDidLoad];

    [self setLimitForDatePicker];
    birthdayTextField.inputView = _dateWithYearPicker;
}
-(void)awakeFromNib
{
    _dateWithYearPicker = [[UIDatePicker alloc] init];
    _dateWithYearPicker.datePickerMode = UIDatePickerModeDate;
    [_dateWithYearPicker addTarget:self action:@selector(datePickerDateDidChange) forControlEvents:UIControlEventValueChanged];
}
-(void)setLimitForDatePicker
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:-16];
    NSDate *minDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    [comps setYear:-110];
    NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    _dateWithYearPicker.minimumDate = minDate;
    _dateWithYearPicker.maximumDate = maxDate;
}

在我启动应用程序之后,点击birthdayTextField,日期选择器似乎没有限制。

欢迎您提出所有建议。

1 个答案:

答案 0 :(得分:1)

我发现了问题。

我切换了最小和最大日期,正确的答案是:

NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:-110]; //before it was 16
    NSDate *minDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    [comps setYear:-16]; // before it was 110
    NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    _dateWithYearPicker.minimumDate = minDate;
    _dateWithYearPicker.maximumDate = maxDate;
相关问题