In one of my recent projects, I was dealing with the development of an iOS app which required the addition of a 'Done' button within a UIDatePicker. Finding a correct and functional solution was a real pain, so I decided to post my solution in case it helps anyone out there. This solution uses UIActionSheet(declared as pickerAction)
-(void)ChooseDP:(int)sender{
pickerAction = [[UIActionSheet alloc] initWithTitle:@"Date"
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake ( 0.0, 44.0, 0.0, 0.0)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
//format datePicker mode. in this example time is used
datePicker.datePickerMode = UIDatePickerModeTime;
[dateFormatter setDateFormat:@"h:mm a"];
//calls dateChanged when value of picker is changed
[datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
toolbarPicker = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolbarPicker.barStyle=UIBarStyleBlackOpaque;
[toolbarPicker sizeToFit];
NSMutableArray *itemsBar = [[NSMutableArray alloc] init];
//calls DoneClicked
UIBarButtonItem *bbitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DoneClicked)];
[itemsBar addObject:bbitem];
[toolbarPicker setItems:itemsBar animated:YES];
[pickerAction addSubview:toolbarPicker];
[pickerAction addSubview:datePicker];
[pickerAction showInView:self.view];
[pickerAction setBounds:CGRectMake(0,0,320, 464)];
}
-(IBAction)dateChanged{
//format date
NSDateFormatter *FormatDate = [[NSDateFormatter alloc] init];
[FormatDate setLocale: [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] ];
//set date format
[FormatDate setDateFormat:@"MM/dd/YYYY"];
//update date textfield
date.text = [FormatDate stringFromDate:[datePicker date]];
}
-(BOOL)closeDatePicker:(id)sender{
[pickerAction dismissWithClickedButtonIndex:0 animated:YES];
[date resignFirstResponder];
return YES;
}
//action when done button is clicked
-(IBAction)DoneClicked{
[self closeDatePicker:self];
datePicker.frame=CGRectMake(0, 44, 320, 416);
}
//returns number of components in pickerview
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
//returns number of rows in date picker
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return 40;
}
No comments:
Post a Comment