How can I show a UIDatePicker inside a Popover on iPad using StoryBoard?

扶醉桌前 提交于 2019-11-30 10:20:38
Pedro Silva

You might want to avoid all the work in the storyboard by creating the ViewController and the DatePicker programmatically:

//build our custom popover view
UIView *v = [[UIView alloc] init];
CGRect pickerFrame = CGRectMake(0, 0, 320, 216);
UIDatePicker *pView=[[UIDatePicker alloc] initWithFrame:pickerFrame];
pView.datePickerMode = UIDatePickerModeDate;

self.datePicker = pView;
[v addSubview:self.datePicker];

UIViewController *popoverContent = [[UIViewController alloc]init];
popoverContent.view = v;


//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);

// dismiss existing popover
if (self.pcDatePicker)
{
    [self.pcDatePicker dismissPopoverAnimated:NO];
    self.pcDatePicker = nil;
}

//create a popover controller with my DatePickerViewController in it
UIPopoverController *popoverControllerForDate = [[UIPopoverController alloc] initWithContentViewController:popoverContent];

//Set the delegate to self to receive the data of the Datepicker in the popover
popoverControllerForDate.delegate = self;

//Adjust the popover Frame to appear where I want
CGRect myFrame = sender.frame;//CGRectMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 320,     200);
myFrame.origin.x = 260;
myFrame.origin.y = 320;

//Present the popover
[popoverControllerForDate presentPopoverFromRect:myFrame
                                          inView:self.view
                        permittedArrowDirections:UIPopoverArrowDirectionAny
                                        animated:YES];

self.pcDatePicker = popoverControllerForDate;

And then use the delegate Method to get the date:

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    self.startDate = self.datePicker.date;
}

Solved

All I have to do is instantiate the StoryBoard Date Picker View Controller like :

...
DatePickerViewController* popoverContent = [[DatePickerViewController alloc] init];

popoverContent =[[UIStoryboard storyboardWithName:@"MainStoryboard"
                                         bundle:nil]
               instantiateViewControllerWithIdentifier:@"DatePickerVC"];
//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);
...

where the identifier is set in StoryBoard Attributes Inspector

and now it is shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!