user1107173
user1107173

Reputation: 10754

UIDatePicker: Add constraint to time

Is there a way to limit/constraint time on the UIDatePicker.

i.e. if I want the picker to show time only from 3:00PM - 8:00PM, nothing before of after that time, is that possible?

Code example would be nice. Thanks!

EDIT

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{


    // **EDIT 2**
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMinute:10];
    [comps setHour:5];
    NSDate *minimumTime = [[NSCalendar currentCalendar] dateFromComponents:comps];


    UIDatePicker *pickerView = [[[UIDatePicker alloc] init] initWithFrame:CGRectMake(0, 40, 320, 216)];

    pickerView.datePickerMode = UIDatePickerModeTime;
    [pickerView setMinimumDate:minimumTime];

    [pickerView setMinuteInterval:15];
    [pickerView setTag: kDatePickerTag1];
    //Add picker to action sheet
    [actionSheet addSubview:pickerView];
    NSArray *subviews = [actionSheet subviews];
}

startTimeLabel is an NSString variable (i.e. 6:30 PM) that should be used as minimum time on the UIPicker.

Image: enter image description here

Upvotes: 1

Views: 940

Answers (1)

Abdullah Shafique
Abdullah Shafique

Reputation: 6918

Use this code:

[datePicker setMaximumDate:yourmaxDate];
[datePicker setMinimumDate:yourminDate];

To create a NSDate:

NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components: NSUIntegerMax fromDate:todaysDate];
[comps setMinute:10];
[comps setHour:5];
[comps setSecond:0];
NSDate *yourminDate = [gregorian dateFromComponents:comps];

Upvotes: 2

Related Questions