如何避免用户在UIDatePicker中选择某个日期?

时间:2010-07-03 11:14:45

标签: iphone uidatepicker

我必须提示用户从CoCoa UIDatePicker中选择日期,但避免他选择星期日和星期六,因为我的目标是让他们选择预约日期

最好的方法应该是以与minimumDate属性相同的方式禁用该日期,但我无法找到如何做到这一点

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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.
}

这样,当选择星期六或星期日的日期时,日期选择器会自动选择周末之后的星期一。

(代码未经测试!)