raptor raptor - 5 months ago 20
iOS Question

How to set Minimum time to appear as default in UIDatepicker everytime

In Datepicker i have set Min and Max time where uidatepicker can scroll for example i have set 3:00PM as minimum time and 8:00PM as maximum time , when i run the app i want the datepicker to display the Minimum time not the current time of the device . I have hard coded UIDatepicker in my project havent used in xib file . I have set Min time but when i switch from control.tag ==1 to 2 the minimum time changes and also when i open the app for first time the datepicker doesnt start from minimum time.

UPDATE :

-(IBAction)notificationButtonChanged:(UIButton *)control
{

if (control.tag == 1)
{
self.selectedButton = control.tag;

[userTimePicker reloadInputViews];

[components setHour:7];;
[components setMinute:00];

NSDate *date1 = [gregorian dateFromComponents:components];

[components setHour:11];
[components setMinute:00];

NSDate *date2 = [gregorian dateFromComponents:components];

[userTimePicker setDatePickerMode:UIDatePickerModeTime];

[userTimePicker setMinimumDate:date1];
[userTimePicker setMaximumDate:date2];

}

if (control.tag == 2)
{
self.selectedButton = control.tag;

[userTimePicker reloadInputViews];

[components setHour:12];
[components setMinute:00];

NSDate *date1 = [gregorian dateFromComponents:components];

[components setHour:17];
[components setMinute:00];

NSDate *date2 = [gregorian dateFromComponents:components];

[userTimePicker setDatePickerMode:UIDatePickerModeTime];

[userTimePicker setMinimumDate:date1];
[userTimePicker setMaximumDate:date2];

}

}

Answer

EDIT:

int startHour = 7;
int endHour = 11;

NSDate *date1 = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date1];
[components setHour: startHour];
[components setMinute: 0];
[components setSecond: 0];
NSDate *startDate = [gregorian dateFromComponents: components];

[components setHour: endHour];
[components setMinute: 0];
[components setSecond: 0];
NSDate *endDate = [gregorian dateFromComponents: components];

[userTimePicker setDatePickerMode:UIDatePickerModeTime];
[userTimePicker setMinimumDate:startDate];
[userTimePicker setMaximumDate:endDate];
[userTimePicker setDate:startDate animated:YES];
[userTimePicker reloadInputViews];