从 Swift 中的任意锚点呈现弹出窗口

Present a popover from an arbitrary anchor point in Swift

我知道如何按照 this answer(对于 iPhone 和 iPad)中的描述从条形按钮项中显示弹出窗口。

我想为任意锚点添加弹出窗口。我看到的其他 SO 答案是针对条形按钮项目或 Objective-C.

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

更新 Swift 3

在情节提要中,添加一个您希望用作弹出窗口的视图控制器。将 Storyboard ID 设置为 "popoverId".

同时向主视图控制器添加一个按钮,并将 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 允许您选择任意点来显示弹出框。

就是这样。现在点击按钮时它应该像这样。

感谢 this article 的帮助。

Swift 3.1 的解决方案:

添加到您的 ViewController UIPopoverPresentationControllerDelegate 委托:

class OriginalViewController: UIViewController, UIPopoverPresentationControllerDelegate

向您的 ViewController 添加一个按钮,然后点击您的按钮,调用此代码:

    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)

更新上面的 func 语法:

func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentatinStyle { 
    return .none 
}

由于某种原因,旧语法仍然允许使用但未激活,并且不会正确实现弹出窗口或锚点。