我在我的IOS应用程序上使用日期选择器,我想知道是否有可能阻止某些日子。例如,我需要阻止一年中的所有星期一,这可能吗?
感谢。
答案 0 :(得分:3)
您唯一能做的就是按照评论中的说明添加自定义UIPickerView,或者按照here
所述实现为事件UIControlEventValueChanged
调用的方法
然后检查有效工作日的新值。你可以通过以下方式获得工作日:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
return [components weekday]; // 1 = Sunday, 2 = Monday, ...
无法隐藏滚轮中的某些日子。
答案 1 :(得分:1)
这是此问题的迅速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)
}
}
答案 2 :(得分:0)
我必须做类似的事情,并且找不到删除日期的方法。然而,我最终做的是,如果选择了无效日期,它将反弹到最近的有效日期,类似于控件处理如果您设置最小日期并尝试选择之前的日期。
-(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];
}
}