how to center a popoverview in swift

前端 未结 10 1742
终归单人心
终归单人心 2020-12-04 16:42

I have the following code to show a popoverview (dialog) without an arrow, which works fine. The only problem is, that the dialog is shown in the top left (IPad). I would li

10条回答
  •  忘掉有多难
    2020-12-04 17:10

    Swift 4.1

    Here is the simple solution:

    Take a public variable var popover

    var popover: UIPopoverPresentationController?
    

    Present YourViewController as popover, use the popover?.sourceRect as mentioned below.

    let storyboard: UIStoryboard = UIStoryboard(name: "YOUR_STORYBOARD", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "YOUR_IDENTIFIER") as! YourViewController
    let navController = UINavigationController(rootViewController: vc)
    navController.modalPresentationStyle = UIModalPresentationStyle.popover
    popover = yourController.popoverPresentationController!
    popover?.sourceRect = CGRect(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY, width: 0, height: 0)
    popover?.sourceView = self.view
    popover?.delegate = self
    popover?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
    vc.preferredContentSize = CGSize(width: width, height: height)
    self.present(navController, animated: true, completion: nil)
    

    use viewWillTransition for view transitions landscape and portrait.

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
         super.viewWillTransition(to: size, with: coordinator)
         popover?.sourceRect = CGRect(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY, width: 0, height: 0)
    }
    

    this will give you popover center aligned to screen in both landscape and portrait. Much flexible while using split view for iPad.

提交回复
热议问题