我在我的 IOS 应用程序上使用日期选择器,我想知道是否可以屏蔽某些日子。例如,我需要屏蔽一年中的所有星期一,这可能吗?
谢谢。
您唯一可以做的就是按照评论中的描述添加自定义 UIPickerView 或实现一个为事件调用的方法
UIControlEventValueChanged
如here
然后检查有效工作日的新值。你可以通过以下方式获得工作日:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
return [components weekday]; // 1 = Sunday, 2 = Monday, ...
有些日子是没办法隐藏在滚轮里的。
这是 Swift 4 对这个问题的回答(Nicholas Harlen 的原始回答):
let datePicker: UIDatePicker = UIDatePicker(frame: .zero)
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)
@objc func datePickerValueChanged(_ sender: UIDatePicker) {
let calender: Calendar = Calendar(identifier: .gregorian)
let weekday = calender.component(.weekday, from: sender.date)
//sunday
if weekday == 1 {
datePicker.setDate(Date(timeInterval: 60*60*24*1, since: sender.date), animated: true)
} else if weekday == 7 {
datePicker.setDate(Date(timeInterval: 60*60*24*(-1), since: sender.date), animated: true)
}
}
我不得不做类似的事情,但找不到删除日期的方法。然而,我最终做的是,如果选择了一个无效日期,它会反弹到最近的有效日期,类似于如果您设置最小日期并尝试选择该日期之前的日期,控件的处理方式。
-(void)init
{
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero];
[datePicker setDatePickerMode:UIDatePickerModeDate];
[datePicker setMinimumDate: [NSDate date]];
[datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
}
-(void)onDatePickerValueChanged:(UIDatePicker *)picker
{
// Work out which day of the week is currently selected.
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:picker.date];
int weekday = [comps weekday];
// Bounce Sundays (weekday=1) forward a day
if (weekday == 1)
{
[datePicker setDate:[NSDate dateWithTimeInterval:60*60*24*1 sinceDate:picker.date] animated: true];
}
// Bounce Saturdays (weekday=7) back a day
else if (weekday == 7)
{
[datePicker setDate:[NSDate dateWithTimeInterval:60*60*24*-1 sinceDate:picker.date] animated: true];
}
}
在 iOS 16 中,我们有一个专用的日历视图 MultiDatePicker,它可以让用户选择多个日期。