Search code examples
swiftxcodeipaduipopovercontrollermac-catalyst

How to grow a popover controller


I have a popover controller in my app for iPad and Mac (using mac catalyst) and I'm trying to figure out how to grow the height of the popover when it's already presented. I've been searching everywhere on how to do this but everything I find is about setting the size before presenting but not after.

While the pop-up is presenting, there's a button in it that should grow the height by 100-150 pixels, but I can not figure out how

Can anyone please help me with this? Thank you in advance!

Here's my popover presenting code:

func openView(sourceView: UIView?, sourceRect: CGRect?) {
    let vc = ViewControllerA()

    //Try popover
    if let sourceView = sourceView,
        let sourceRect = sourceRect {
            vc.modalPresentationStyle = .popover
            
            if let popover = vc.popoverPresentationController {
                vc.preferredContentSize = return CGSize(width: 390, height: 390)
                vc.presentationController?.delegate = self

                popover.sourceView = sourceView
                popover.sourceRect = sourceRect
                popover.permittedArrowDirections = [.up, .left]

                self.present(vc, animated: true, completion: nil)
                return
            }
        }


    //present it normally if there's no source view
    vc.modalPresentationStyle = .overCurrentContext
    vc.modalTransitionStyle = .crossDissolve

    self.present(vc, animated: true, completion: nil)
}


Solution

  • To change a size of your presented controller in popover view you should modify its preferredContentSize property:

    @IBAction func showPopover(_ sender: UIButton) {
        // Create controller
        guard let controller = storyboard?.instantiateViewController(withIdentifier: "Popover") else {
            return
        }
        controller.modalPresentationStyle = .popover
        controller.preferredContentSize = CGSize(width: 200, height: 200)
        
        // Configure popover
        guard let popover = controller.popoverPresentationController else {
            return
        }
        popover.permittedArrowDirections = .up
        popover.sourceView = self.view
        popover.sourceRect = sender.frame
        popover.delegate = self
        present(controller, animated: true, completion: nil)
        
        // Change height after 3 secs
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            controller.preferredContentSize = CGSize(width: 200, height: 400)
        }
    }