6

我在我的 IOS 应用程序上使用日期选择器,我想知道是否可以阻止某些日子。例如,我需要阻止一年中的所有星期一,这可能吗?

谢谢。

4

3 回答 3

4

您唯一能做的就是添加自定义 UIPickerView 如评论中所述或实现为事件调用的方法,如此UIControlEventValueChanged所述

然后检查有效工作日的新值。您可以通过以下方式获得工作日:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
return [components weekday]; // 1 = Sunday, 2 = Monday, ...

无法在滚轮中隐藏某些日子。

于 2012-08-31T06:39:44.953 回答
3

这是该问题的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)
    }
}
于 2018-11-29T08:14:00.683 回答
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];
    }
}
于 2015-01-23T01:38:52.797 回答