在Swift中从任意锚点展示一个弹出窗口

11

我知道如何按照这个答案的描述(适用于iPhone和iPad)从一个工具栏按钮项中弹出一个气泡。

在此输入图片描述

我想为任意锚点添加一个气泡。我看到的其他SO答案都是针对工具栏按钮项或使用Objective-C编写的。

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

4个回答

32

更新至Swift 3

在Storyboard中,添加一个视图控制器作为弹出视图。将Storyboard ID设置为"popoverId"。

enter image description here

同时,在主视图控制器中添加一个按钮,并将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

感谢这篇文章的帮助。


1
popController.popoverPresentationController?.barButtonItem = sender - Bogdan Bogdanov
1
你好,你能告诉我如何制作一个像你展示的小视图控制器吗? - PeterLai
@PeterLai,我已经有一段时间没有处理这个问题了。我现在不记得我当时做了什么。请查看此问题:https://dev59.com/CKLia4cB1Zd3GeqPoMNn - Suragch

10

Swift 3.1的解决方案:

UIPopoverPresentationControllerDelegate代理添加到您的ViewController中:

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)

3

上面的函数语法更新如下:

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

由于某些原因,旧的语法仍然被允许,但已经不起作用了,并且无法正确实现弹出窗口或锚点。


-1
你可以为弹出窗口添加高度和宽度。
popController.preferredContentSize = CGSize(width: 200, height: 100)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接