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)
设置sourceView和sourceRect允许您选择任意点来显示弹出窗口.
而已.现在,当按下按钮时,它应该是这样的.
感谢这篇文章的帮助.
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)