UIDatePicker设置最大日期

时间:2013-02-04 19:53:26

标签: ios xcode

我正在使用此代码阻止用户超出我设置的限制:

在视图中加载:

NSDate *Date=[NSDate date];
[DatePickerForDate setMinimumDate:Date];
[DatePickerForDate setMaximumDate:[Date dateByAddingTimeInterval: 63072000]]; //time interval in seconds

这个方法:

- (IBAction)datePickerChanged:(id)sender{
if ( [DatePickerForDate.date timeIntervalSinceNow ] < 0 ){
    NSDate *Date=[NSDate date];
    DatePickerForDate.date = Date;
}

if ( [DatePickerForDate.date timeIntervalSinceNow ] > 63072000){
    NSDate *Date=[NSDate date];
    DatePickerForDate.date = Date;
}
}

第一部分起作用(带有&lt; 0的那部分),并返回当前日期,但是一个&gt; 63072000,有时工作,有时不工作。顺便说一句63072000约为2年。有什么想法吗?

1 个答案:

答案 0 :(得分:11)

我尝试使用UIDatePicker,最长日期为一个月:

NSDate* now = [NSDate date] ;
// Get current NSDate without seconds & milliseconds, so that I can better compare the chosen date to the minimum & maximum dates.
NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDateComponents* nowWithoutSecondsComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:now] ;
NSDate* nowWithoutSeconds = [calendar dateFromComponents:nowWithoutSecondsComponents] ;
//  UIDatePicker* picker ;
picker.minimumDate = nowWithoutSeconds ;

NSDateComponents* addOneMonthComponents = [NSDateComponents new] ;
addOneMonthComponents.month = 1 ;
NSDate* oneMonthFromNowWithoutSeconds = [calendar dateByAddingComponents:addOneMonthComponents toDate:nowWithoutSeconds options:0] ;
picker.maximumDate = oneMonthFromNowWithoutSeconds ;

我发现:

  • 当您第一次尝试选择超出最小和最大范围的日期时,UIDatePicker会自动向后滚动“范围内”。
  • 如果您再次选择超出范围的日期,则选择器不会向后滚动,允许您选择超出范围的日期。
  • 如果选择器的选定日期超出范围,则其date属性将返回最接近范围的日期。
  • 当您致电setDate:setDate:animated:时,如果您传递的日期与选择器的date属性返回的日期完全相同,则选择器将不执行任何操作。

考虑到这一点,这里有一个方法,当Picker的值发生变化时你可以调用它来阻止你选择超出范围的日期:

- (IBAction) datePickerChanged:(id)sender {
    // When `setDate:` is called, if the passed date argument exactly matches the Picker's date property's value, the Picker will do nothing. So, offset the passed date argument by one second, ensuring the Picker scrolls every time.
    NSDate* oneSecondAfterPickersDate = [picker.date dateByAddingTimeInterval:1] ;
    if ( [picker.date compare:picker.minimumDate] == NSOrderedSame ) {
        NSLog(@"date is at or below the minimum") ;
        picker.date = oneSecondAfterPickersDate ;
    }
    else if ( [picker.date compare:picker.maximumDate] == NSOrderedSame ) {
        NSLog(@"date is at or above the maximum") ;
        picker.date = oneSecondAfterPickersDate ;
    }
}

以上ifelse if部分几乎相同,但我将它们分开,以便我可以看到不同的NSLog,并且还可以更好地调试。

Here's the working project在GitHub上。