UIPopover中的UIDatePicker
我已经search了整个互联网(也许我有点夸张)的教程,如何将DatePicker放入UIPopover并显示在iPad应用程序。 我已经尝试创build一个viewcontroller,将datepicker放在视图控制器,然后:
self.popover = [[UIPopoverController alloc] initWithContentViewController:sa];
(sa是我创build的viewcontroller的名称),但这不起作用,应用程序崩溃。 谁能帮忙?
尝试使用下面的代码。 它会正常工作:
Objective-C的
- (IBAction)showDatePicker:(UIButton *)sender { UIDatePicker *datePicker = [[UIDatePicker alloc]init];//Date picker datePicker.frame = CGRectMake(0, 0, 320, 216); datePicker.datePickerMode = UIDatePickerModeDateAndTime; [datePicker setMinuteInterval:5]; [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];//need to implement this method in same class UIView *popoverView = [[UIView alloc] init]; //view popoverView.backgroundColor = [UIColor clearColor]; [popoverView addSubview:datePicker]; // here you can add tool bar with done and cancel buttons if required UIViewController *popoverViewController = [[UIViewController alloc] init]; popoverViewController.view = datePicker; popoverViewController.view.frame = CGRectMake(0, 0, 320, 216); popoverViewController.modalPresentationStyle = UIModalPresentationPopover; popoverViewController.preferredContentSize = CGSizeMake(320, 216); popoverViewController.popoverPresentationController.sourceView = sender; // source button popoverViewController.popoverPresentationController.sourceRect = sender.bounds; // source button bounds //popoverViewController.popoverPresentationController.delegate = self; [self presentViewController:popoverViewController animated:YES completion:nil]; } - (void)dateChanged:(UIDatePicker *)datePicker { NSLog(@"DATE :: %@", datePicker.date); }
Swift3
@IBAction func showDatePicker(_ sender: UIButton) { let datePicker = UIDatePicker()//Date picker datePicker.frame = CGRect(x: 0, y: 0, width: 320, height: 216) datePicker.datePickerMode = .dateAndTime datePicker.minuteInterval = 5 datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged) let popoverView = UIView() popoverView.backgroundColor = UIColor.clear popoverView.addSubview(datePicker) // here you can add tool bar with done and cancel buttons if required let popoverViewController = UIViewController() popoverViewController.view = popoverView popoverViewController.view.frame = CGRect(x: 0, y: 0, width: 320, height: 216) popoverViewController.modalPresentationStyle = .popover popoverViewController.preferredContentSize = CGSize(width: 320, height: 216) popoverViewController.popoverPresentationController?.sourceView = sender // source button popoverViewController.popoverPresentationController?.sourceRect = sender.bounds // source button bounds self.present(popoverViewController, animated: true, completion: nil) } func dateChanged(_ datePicker: UIDatePicker) { print("DATE :: \(datePicker.date)") }
现在,你已经标记了iPhone它可以清楚地认为你正在尝试在iPhone
使用UIPopoverController
但UIPopoverController
只适用于iPad
。 所以它会导致崩溃,因为iPhone不能识别该控制器。