Reputation: 1575
I've created a UIDatePicker so that a user can select their birthday and I've tried to set the minimum and maximum allowable dates. However, setting the min/max dates like I've done below merely grays out the dates that are out of bounds but you can still scroll to them. How do I prevent the datepicker from scrolling to these dates instead of just merely graying them out?
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:1914];
NSDate *minimumDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSDateComponents *compsMax = [[NSDateComponents alloc] init];
[compsMax setDay:31];
[compsMax setMonth:12];
[compsMax setYear:2013];
NSDate *maximumDate = [[NSCalendar currentCalendar] dateFromComponents:compsMax];
birthdayPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(220, 150, 500, 10)];
[birthdayPicker setDatePickerMode:UIDatePickerModeDate];
[birthdayPicker setMinimumDate:minimumDate];
[birthdayPicker setMaximumDate:maximumDate];
[birthdayPicker reloadInputViews];
[self addSubview:birthdayPicker];
Upvotes: 0
Views: 1044
Reputation: 6192
I'll admit, it's not the best, but give it a shot, maybe it can be improved:
In viewDidLoad
[birthdayPicker addTarget:self
action:@selector(pickerValueChanged:)
forControlEvents:UIControlEventValueChanged];
Somewhere else in code
- (IBAction)pickerValueChanged:(id)sender {
dispatch_async(dispatch_get_main_queue(), ^{
UIDatePicker *datePicker = (UIDatePicker *)sender;
if ([datePicker.date compare:datePicker.maximumDate] == NSOrderedDescending) {
datePicker.date = datePicker.maximumDate;
}
else if ([datePicker.date compare:datePicker.minimumDate] == NSOrderedAscending) {
datePicker.date = datePicker.minimumDate;
}
});
}
Upvotes: 1