ios - 从 Swift 中的任意 anchor 呈现弹出窗口

标签 ios swift popover

我知道如何按照 this answer 中的描述从条形按钮项目中呈现弹出窗口(适用于 iPhone 和 iPad)。

enter image description here

我想为任意 anchor 添加一个弹出框。我看到的其他 SO 答案是针对栏按钮项或在 Objective-C 中。

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

最佳答案

针对 Swift 3 进行了更新

在 Storyboard中,添加一个您希望作为弹出窗口的 View Controller 。将 Storyboard ID 设置为“popoverId”。

enter image description here

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

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

enter image description here

感谢this article寻求帮助。

关于ios - 从 Swift 中的任意 anchor 呈现弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38797836/

相关文章:

ios - 如何 JSON 序列化包含一系列 CGPath 的 NSData

iphone - 在 ios6 中从 iPhone 相机捕获全景图像

swift - 当我将 tableView 向下拖动到某个点时如何隐藏它,Swift

ios - 允许用户使用来自不同 View Controller 中标签的文本创建新的 tableViewCells?

swift - 将 CDN 用于移动 Swift 应用程序

jquery - bootstrap 弹出按钮单击事件无法使用 jquery 工作

android - 如何在 native 中更改用户当前位置的蓝点颜色或图像

iOS/核心数据 : Can value for key access relationships?

javascript - Bootstrap 弹出窗口不起作用

ios - 如何从 Popover 调用主视图 Controller 的方法?