我使用此代码来阻止用户超出我设置的限制:
在视图中确实加载了:
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;
}
}
第一部分有效( 63072000 的部分有时有效,有时无效。顺便说一下63072000大约是2年。有任何想法吗?
我尝试使用 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:
or 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
and else if
部分几乎相同,但我将它们分开,以便我可以看到不同的 NSLog,也可以更好地调试。
这是工作项目在 GitHub 上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)