今から1か月の maximumDate で 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
それを念頭に置いて、ピッカーの値が変更されたときに呼び出して、範囲外の日付を選択できないようにするメソッドを次に示します。
- (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 ;
}
}
上記if
とelse if
セクションはほぼ同じですが、別の NSLog を確認できるように、またデバッグを改善するために、別々にしました。
GitHubの作業中のプロジェクトは次のとおりです。