ios 如何在 UIDatePicker 中禁用未来的日期、月份和年份?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23910666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable future dates,months and year in UIDatePicker?
提问by Ram
How to hide the future dates in UIDatePicker for user choosing only past and current year of birthdays.
如何在 UIDatePicker 中隐藏未来日期,以便用户仅选择过去和当前的生日年份。
I search lot of source but I can't get the desired result.
我搜索了很多来源,但无法获得所需的结果。
Here is my code,
这是我的代码,
dateofBirthDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
dateofBirthDatePicker.datePickerMode = UIDatePickerModeDate;
[dateofBirthDatePicker setBackgroundColor:DATE_PICKER_GRAY_COLOR];
// UILabel *label = [UILabel appearanceWhenContainedIn:[UITableView class],[UIDatePicker class], nil];
// label.font = HELVETICA_NEUE(24);
// label.textColor = GREEN_COLOR;
[dateofBirthDatePicker addTarget:self
action:@selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
dateofbirthTextField.inputView = dateofBirthDatePicker;
[self datePickerToolBar];
}
- (void)LabelChange:(id)sender
{
NSDateFormatter *dateFormat= [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
dateofbirthTextField.text = [NSString stringWithFormat:@"%@",
[dateFormat stringFromDate:dateofBirthDatePicker.date]];
}
If any body know the solution kindly give the suggestion. I really appreciate to you.
如果任何机构知道解决方案,请提出建议。我真的很感激你。
回答by Mawoon
Here is the simple code to prevent future date selection:
dateofBirthDatePicker.maximumDate=[NSDate date];
In Swift :
dateofBirthDatePicker.maximumDate = Date()
回答by Phil Hudson
In Swift 2:
在 Swift 2 中:
self.datePicker.maximumDate = NSDate()
self.datePicker.maximumDate = NSDate()
In Swift 3:
在 Swift 3 中:
self.datePicker.maximumDate = Date()
self.datePicker.maximumDate = Date()
回答by Keshav Gera
In Swift 4.0.3 Xcode 9
在 Swift 4.0.3 Xcode 9 中
Hide Future Date
隐藏未来日期
self.picker.maximumDate = Date()
回答by Greg
You can use setMaximumDate: and setMinimumDate: on UIDatePicker object:
您可以在 UIDatePicker 对象上使用 setMaximumDate: 和 setMinimumDate: :
[dateofBirthDatePicker setMaximumDate:[NSDate date]]; // The max date will be today
// Optional you can set up min date as well
[dateofBirthDatePicker setMinimumDate:yourMinDate];
回答by Pancho
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1];
NSDate *maxDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps setYear:-30];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[datePicker setMaximumDate:maxDate];
[datePicker setMinimumDate:minDate];