Displaying UIDatePicker as Popover within UITableView on iPhone

1.1k views Asked by At

I would like display a date picker with a UIModalPresentationPopover presentation style, and while it's working fine on an iPad, it results in a black screen when displayed on an iPhone. Edit: Specifically, it is simply presented full screen, so the effect is a black screen unless I add colours to elements manually. The default colours work fine for Popover presentation.

The code generating the picker and the popover is:

let datePicker = UIDatePicker()
datePicker.datePickerMode = .DateAndTime
datePicker.minuteInterval = 5

let vc = UIViewController()
vc.view.addSubview(datePicker!)
vc.preferredContentSize = datePicker.frame.size
vc.modalPresentationStyle = .Popover

let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1))
let ppc = vc.popoverPresentationController
ppc?.delegate = self
ppc?.sourceRect = cell.accessoryView!.frame
ppc?.sourceView = cell

self.presentViewController(vc, animated: true, completion: nil)

The value of cell appears correct on both types of devices, but I notice that the size of the view of the presented viewController gets messed up on the iPhone. After presentation is finished, the value of preferredContentSize property is (320.0, 216.0) on both devices, but view.frame.size becomes (320.0, 568.0) on the iPhone (which is full screen on iPhone 5, and it acts similarly on iPhone as well), while on iPad it still matches the preferred size.

Looks great on iPad:

Looks great on iPad

I've had no trouble presenting the same kind of UI from a UIViewController that was not UITableViewController. Is there anything else that needs to be done to allow this style of presentation with a tableView on an iPhone?

Edit Fixed. To allow this, need to add a method to the presenting controller:

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
    return .None
}
1

There are 1 answers

0
EmilioPelaez On

This is what I found on the docs from UIViewController

modalPresentationStyle

The presentation style determines how a modally presented view controller is displayed onscreen. In a horizontally compact environment, modal view controllers are always presented full-screen

What you can do is, on the iPhone, set the backgroundColor of the view to black with `.15 alpha, and position the picker at the bottom.

You might need to set modalPresentationStyle to UIModalPresentationOverFullScreen, because otherwise it removes the views underneath.