Swift 触摸背景时弹出窗口关闭

Swift Popover closing when touching background

我有一个正在调用的弹出窗口,我希望关闭弹出窗口的唯一方法是单击“关闭”按钮,而不是在背景上点击。目前我启动弹出窗口的代码是这样的:

 let popover = storyboard?.instantiateViewController(withIdentifier: "PopoverVC") as! PopOverViewController

        popover.modalPresentationStyle = .popover
        popover.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate


        popover.popoverPresentationController?.sourceView = self.view
        popover.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)

        popover.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

        popoverPresentationController?.passthroughViews = nil



        dimView.isHidden = false

        popover.dimView = self.dimView

        self.present(popover, animated: false)

我在背景中有一个 UIview,当弹出窗口出现时,我用它来使背景变暗,但是当你点击背景时,它会关闭弹出窗口。我怎样才能让弹出窗口保持打开状态?我认为 popoverPresentationController?.passthroughViews = nil 应该可以解决这个问题,但它没有。

编辑:

添加我的 PopOverViewController Class:

    class PopOverViewController: UIViewController, UIPopoverPresentationControllerDelegate {


    var dimView:UIView?

    override func viewDidLoad() {
        super.viewDidLoad()


        // Do any additional setup after loading the view.
    }

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


    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {

        print ("test")

        return false
    }


    @IBAction func closeButton(_ sender: Any) {

        self.dismiss(animated: false, completion: nil)

        dimView?.isHidden = true


    }

}

您需要使用演示控制器的委托。您已经在分配 self,只需实施以下委托方法即可。

extension SelfsType: UIPopoverPresentationControllerDelegate {

    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
       /* This disables the automatic dismissal, but you can make it conditional, too. Such as if the user entered enough information, etc */
       return false
    }
}

其中 SelfsType 是在

上下文中使用的 self 的 class
popover.popoverPresentationController?.delegate = self as? UIPopoverPresentationControllerDelegate

您的代码不包含该内容。