UIDatePicker最小/最大日期

时间:2014-07-02 19:33:51

标签: ios objective-c date datepicker uikit

我已经创建了一个UIDatePicker,以便用户可以选择他们的生日,并且我已尝试设置最小和最大允许日期。但是,设置最小/最大日期就像我在下面所做的那样仅仅会使超出范围的日期变灰,但您仍然可以滚动到它们。如何阻止日期选择器滚动到这些日期而不仅仅是将它们变灰?

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:1914];
NSDate *minimumDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

NSDateComponents *compsMax = [[NSDateComponents alloc] init];
[compsMax setDay:31];
[compsMax setMonth:12];
[compsMax setYear:2013];
NSDate *maximumDate = [[NSCalendar currentCalendar] dateFromComponents:compsMax];

birthdayPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(220, 150, 500, 10)];
[birthdayPicker setDatePickerMode:UIDatePickerModeDate];
[birthdayPicker setMinimumDate:minimumDate];
[birthdayPicker setMaximumDate:maximumDate];
[birthdayPicker reloadInputViews];
[self addSubview:birthdayPicker];

1 个答案:

答案 0 :(得分:1)

我承认,它不是最好的,但要试一试,也许可以改进:

viewDidLoad

[birthdayPicker addTarget:self
                   action:@selector(pickerValueChanged:)
         forControlEvents:UIControlEventValueChanged];

代码中的其他地方

- (IBAction)pickerValueChanged:(id)sender {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIDatePicker *datePicker = (UIDatePicker *)sender;
        if ([datePicker.date compare:datePicker.maximumDate] == NSOrderedDescending) {
            datePicker.date = datePicker.maximumDate;
        }
        else if ([datePicker.date compare:datePicker.minimumDate] == NSOrderedAscending) {
            datePicker.date = datePicker.minimumDate;
        }

    });
}