从Swift中的任意锚点展示popover

我知道如何在酒吧button项目中呈现popup式窗口,如本答案中所述 (适用于iPhone和iPad)。

在这里输入图像说明

我想添加一个任意锚点的popup窗口。 我看到的其他答案是用于栏button项目或Objective-C中的。

我刚刚学会了如何做到这一点,所以我在下面添加我自己的答案。

更新了Swift 3

在故事板中,添加一个您想成为popup窗口的视图控制器。 将情节提要ID设置为“popoverId”。

在这里输入图像说明

还要添加一个button到你的主视图控制器,并将IBAction连接到下面的代码。

import UIKit class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBAction func buttonTap(sender: UIButton) { // get a reference to the view controller for the popover let popController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popoverId") // set the presentation style popController.modalPresentationStyle = UIModalPresentationStyle.popover // set up the popover presentation controller popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up popController.popoverPresentationController?.delegate = self popController.popoverPresentationController?.sourceView = sender // button popController.popoverPresentationController?.sourceRect = sender.bounds // present the popover self.present(popController, animated: true, completion: nil) } // UIPopoverPresentationControllerDelegate method func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { // Force popover style return UIModalPresentationStyle.none } } 

设置sourceViewsourceRect可以让你select一个任意的点来显示popover。

而已。 现在,当点击button时,它应该像这样。

在这里输入图像说明

感谢这篇文章的帮助。

Swift 3.1的解决scheme:

添加到你的ViewController UIPopoverPresentationControllerDelegate委托:

 class OriginalViewController: UIViewController, UIPopoverPresentationControllerDelegate 

向你的ViewController添加一个button,并点击你的button,调用这个代码:

  let controller = MyPopViewController() controller.modalPresentationStyle = UIModalPresentationStyle.popover let popController = controller.popoverPresentationController popController?.permittedArrowDirections = .any popController?.delegate = self popController?.sourceRect = (self.myButton?.bounds)! popController?.sourceView = self.myButton self.present(controller, animated: true, completion: nil)