在 Swift 中实施 PopOver

Implement PopOver in Swift

我想显示一个弹出菜单,但不使用 nib.I 不喜欢使用 nib,因为实现简单功能的委托令人头疼。我成功地使用 modalPresentationStyle 作为 PopoverViewController 显示为 Popover 并且它与下面的代码一起工作正常。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btnShowPopOver: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func showPopUP(sender: AnyObject) {

        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let popVC = storyboard.instantiateViewControllerWithIdentifier("pop")as! PopViewController
        popVC.modalPresentationStyle = UIModalPresentationStyle.Popover
        popVC.preferredContentSize = CGSizeMake(320, 240)
        popVC.popoverPresentationController!.delegate = self


        let popOverController = popVC.popoverPresentationController
        popOverController!.sourceView = sender as! UIView // where to stick the bar item in which view
        popOverController!.sourceRect = CGRectMake(70,30, 0, 0) //where to stick the bar

        popOverController?.permittedArrowDirections = nil
        self.presentViewController(popVC, animated: true, completion: nil)


    }




}


extension ViewController :UIPopoverPresentationControllerDelegate {

    func adaptivePresentationStyleForPresentationController(PC: UIPresentationController) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }


    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {

        var controller = popoverPresentationController.presentedViewController as! PopViewController
         println(" this is data from pop view controller \(controller.textField.text)")

    }


}

Apple doc

Popover controllers are for use exclusively on iPad devices. Attempting to create one on other devices results in an exception.

我在真实设备 iphone-6 上测试过它,它工作正常..我很喜欢这个 Popover

根据 Apple 文档,我应该使用 Popover 还是不应该使用?由于它在 iphone 中运行良好,我的应用程序以后会因为使用它而被拒绝吗?

Since iOS8 we are now able to create popovers, that will be the same on iPhone, as on iPad, which would be especially awesome for those who make universal apps, thus no need to make separate views or code.

来源:UIPopoverController for iphone not working?

看看这个答案:

iOS 9 的每个版本文档中,他们也这样说:

UIPopoverController class 用于管理弹出窗口中内容的显示。您使用弹出窗口来临时显示信息。弹出框内容叠加在现有内容之上,背景自动变暗。弹出窗口保持可见,直到用户点击弹出窗口外部 window 或您明确关闭它。 Popover 控制器专供 iPad 设备 使用。尝试在其他设备上创建一个会导致异常。

编辑

我认为您已经使用了 iOS 8.0 及更高版本中可用的 UIPopoverPresentationController

UIPopoverControllerUIPopoverPresentationController 是 Apple 提供的两种不同的东西。