我知道如何按照这个答案的描述(适用于iPhone和iPad)从一个工具栏按钮项中弹出一个气泡。
我想为任意锚点添加一个气泡。我看到的其他SO答案都是针对工具栏按钮项或使用Objective-C编写的。
我刚学会了如何做到这一点,因此在下面添加了自己的答案。
更新至Swift 3
在Storyboard中,添加一个视图控制器作为弹出视图。将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
}
}
设置sourceView
和sourceRect
是让你可以选择任意一个点以显示弹出窗口。
就这样。现在当按钮被点击时,它应该会像这样。
感谢这篇文章的帮助。
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)
上面的函数语法更新如下:
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentatinStyle {
return .none
}
由于某些原因,旧的语法仍然被允许,但已经不起作用了,并且无法正确实现弹出窗口或锚点。
popController.preferredContentSize = CGSize(width: 200, height: 100)
popController.popoverPresentationController?.barButtonItem = sender
- Bogdan Bogdanov