UIPopoverPresentationController programmatically created fills the screen

815 Views Asked by At

The popup that I am creating programmatically fills the screen. As you can see from the example code, I have tried many ways to limit its size, but none are working. Also, the delegate methods are not being called. Any ideas? I have used CALayer successfully in the past for this kind of thing, but thought this would be simpler - maybe not.

@objc func touchDownHandler(sender: UISlider) {
    let popoverController = UIViewController()
    popoverController.view.backgroundColor = .red
    popoverController.view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
    let textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    textLabel.text = "Hello World"
    textLabel.backgroundColor = .green
    popoverController.view.addSubview(textLabel)

    popoverController.modalPresentationStyle = UIModalPresentationStyle.popover
    popoverController.preferredContentSize = CGSize(width: 200, height: 200)

    if let popoverPresentation = popoverController.popoverPresentationController {
        popoverPresentation.delegate = self
        popoverPresentation.sourceRect = sender.frame
        popoverPresentation.popoverLayoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 210, right: 210)
        popoverPresentation.backgroundColor = .blue
        self.controller.present(popoverController, animated: true, completion: {
            print("pop over is visible")
        })
    }
}
1

There are 1 best solutions below

0
On

Keep in mind that, as per Apple documentation, "In a horizontally compact environment, the .popover option behaves the same as UIModalPresentationStyle.fullScreen." https://developer.apple.com/documentation/uikit/uimodalpresentationstyle/popover