2

Link to my github account with files, simply download zip: https://github.com/jzhang172/modalTest

When I click on the "popover" link, I would like to center the popover in the center of the screen.

I tried referencing some stackoverflow questions such as: how to center a popoverview in swift

but no luck. I'm a noob in swift and I'm only using swift, not objective C.

Screenshot of what I see: enter image description here

Community
  • 1
  • 1
Snorlax
  • 4,425
  • 8
  • 37
  • 68

3 Answers3

2

Replacing

controller?.sourceRect = CGRectMake(0.0, self.view.layer.bounds.height * 0.5,0.0,0.0)

with

controller?.sourceRect = CGRectMake(self.view.layer.bounds.width * 0.5, self.view.layer.bounds.height * 0.5,0.0,0.0)

will center the popover content horizontally and vertically.

1

You can center the UIPopover in your view with the code below.

let controller = vc.popoverPresentationController
controller?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
controller?.sourceView = self.view
controller?.sourceRect = CGRectMake(0.0, self.view.layer.bounds.height * 0.5,0.0,0.0)
vc.preferredContentSize=CGSize(width: 400, height: 200)
ZGski
  • 2,398
  • 1
  • 21
  • 34
  • Thank you, question though, it seems to only work if the size of the popover is as I set it, but if I set the last line to:vc.preferredContentSize=CGSize(width: 300, height: 100), it is center vertically but not horizontally, any idea how to fix that? – Snorlax May 13 '16 at 16:11
0

Swift 3:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let popoverPresentationController = segue.destination.popoverPresentationController {
        let controller = popoverPresentationController
        controller.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        controller.sourceView = self.view
        controller.sourceRect = CGRect(x: UIScreen.main.bounds.width * 0.5 - 200, y: UIScreen.main.bounds.height * 0.5 - 100, width: 400, height: 200)
        segue.destination.preferredContentSize=CGSize(width: 400, height: 200)
    }
}
instanceof
  • 1,404
  • 23
  • 30