问题
I am using UIDatePicker control in my project. Added the UIDatePicker in xib file, and programmatically setting the constraints such as minimumDate, maximumDate to the datePicker. This is working fine in simulator, but in device I am able to select any date in datePicker.
Sample code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.datePicker setMinimumDate:[NSDate date]];
[self.datePicker setMaximumDate:[[NSDate date] dateByAddingTimeInterval:3*24*60*60]];
}
screenshot:
Note: I am working on xcode5 - DP6.
Thanks in advance.
回答1:
Add an action for the UIControlEventValueChanged
event on the UIDatePicker
and implement checks to see if the selected date is greater than maximum date or less then the minimum date and set the date accordingly, like so:
- (IBAction)dateValueChanged:(id)sender
{
NSTimeInterval date = [self.datePicker.date timeIntervalSince1970];
NSTimeInterval maxmimumDate = [self.datePicker.maximumDate timeIntervalSince1970];
NSTimeInterval minimumDate = [self.datePicker.minimumDate timeIntervalSince1970];
if (date < minimumDate) {
self.datePicker.date = self.datePicker.minimumDate;
}
if (date > maxmimumDate) {
self.datePicker.date = self.datePicker.maximumDate;
}
// Use the selected date
NSLog(@"%@", self.datePicker.date);
}
This will cause the UIDatePicker
to scroll to the max/min date if you select a date outside the range.
来源:https://stackoverflow.com/questions/19024792/uidatepicker-constraints-not-working-in-device