从Swift中的任意锚点呈现一个popover

Sur*_*gch 8 popover ios swift

我知道如何从条形按钮项目中呈现弹出窗口,如本答案中所述(适用于iPhone和iPad).

在此输入图像描述

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

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

Sur*_*gch 26

针对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
    }
}
Run Code Online (Sandbox Code Playgroud)

设置sourceViewsourceRect允许您选择任意点来显示弹出窗口.

而已.现在,当按下按钮时,它应该是这样的.

在此输入图像描述

感谢这篇文章的帮助.


Kev*_*OUX 9

Swift 3.1的解决方案:

添加到ViewController UIPopoverPresentationControllerDelegate委托:

class OriginalViewController: UIViewController, UIPopoverPresentationControllerDelegate
Run Code Online (Sandbox Code Playgroud)

向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)
Run Code Online (Sandbox Code Playgroud)