如何在iOS版UIDatePicker中锁定日期

g2ieeal7  于 2023-03-14  发布在  iOS
关注(0)|答案(4)|浏览(178)

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

rpppsulh

rpppsulh1#

您唯一能做的就是添加一个定制的UIPickerView(如注解中所述),或者实现一个为事件UIControlEventValueChanged调用的方法(如此处所述
然后检查一个有效工作日的新值.你可以用以下方法得到工作日:

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

没有办法在滚动轮中隐藏某些日期。

gg58donl

gg58donl2#

以下是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)
    }
}
dldeef67

dldeef673#

我不得不做一些类似的事情,但找不到删除日期的方法。然而,我最终做的是,如果选择了一个无效的日期,它会反弹到最近的一天是有效的,类似于如何控制处理,如果你设置了一个最小日期,并试图选择一个日期之前。

-(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];
    }
}
xqkwcwgp

xqkwcwgp4#

在iOS 16中,我们有一个专用的日历视图MultiDatePicker,可以让用户选择多个日期。
https://sarunw.com/posts/swiftui-multidatepicker/

相关问题