我必须提示用户从可可 UIDatePicker 中选择日期,但要避免他选择周日和周六,因为我的目标是让他们选择约会日期
最好的方法应该是禁用该日期,以与 minimumDate 属性相同的方式,但我无法找到如何做到这一点
我必须提示用户从可可 UIDatePicker 中选择日期,但要避免他选择周日和周六,因为我的目标是让他们选择约会日期
最好的方法应该是禁用该日期,以与 minimumDate 属性相同的方式,但我无法找到如何做到这一点
你可以这样做:
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvent:UIControlEventValueChanged];
实施dateChanged
:
- (void)dateChanged:(id)sender {
UIDatePicker *datePicker = (UIDatePicker *)sender;
NSDate *pickedDate = datePicker.date;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:pickedDate];
NSInteger weekday = [weekdayComponents weekday];
[gregorian release];
if (weekday == 1 || weekday == 7) { // Sunday or Saturday
NSDate *nextMonday = nil;
if (weekday == 1)
nextMonday = [pickedDate dateByAddingTimeInterval:24 * 60 * 60]; // Add 24 hours
else
nextMonday = [pickedDate dateByAddingTimeInterval:2 * 24 * 60 * 60]; // Add two days
[datePicker setDate:nextMonday animated:YES];
return;
}
// Do something else if the picked date was NOT on Saturday or Sunday.
}
This way, when a date is picked that is either on a Saturday or Sunday, the date picker automatically selects the Monday after the weekend.
(代码未经测试!)