Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

ios - UIDatePicker min/max date

I've created a UIDatePicker so that a user can select their birthday and I've tried to set the minimum and maximum allowable dates. However, setting the min/max dates like I've done below merely grays out the dates that are out of bounds but you can still scroll to them. How do I prevent the datepicker from scrolling to these dates instead of just merely graying them out?

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll admit, it's not the best, but give it a shot, maybe it can be improved:

In viewDidLoad

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

Somewhere else in code

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

    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...