PopoverviewController like subview iOS swift

 Problem:

I want to show my popoverviewcontroller as my view's subview and tap on outside it wants to be closed.

How can i achieve that?


Solution:

extension MyViewController:UIPopoverPresentationControllerDelegate {

    // MARK: - popoverPresentationController delegate

    public func adaptivePresentationStyle(for controller: UIPresentationControllertraitCollectionUITraitCollection) -> UIModalPresentationStyle {

        return UIModalPresentationStyle.none

    }



}


You can add the extension for your viewController for show as subview it must want to be model presentation style as none.

    func openpopover(_ sender: UIBarButtonItem){

        let popController = Storyboard.instance.instantiateViewController(withIdentifier: MyViewController.storyboardIDasMyViewController

        popController.preferredContentSize = CGSize(width: 320, height: 150)

        

        // set the presentation style

        popController.modalPresentationStyle = UIModalPresentationStyle.popover

        popController.popoverPresentationController?.dimmingView?.backgroundColor = UIColor.black.withAlphaComponent(0.3)

        // set up the popover presentation controller

        popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.any

        popController.popoverPresentationController?.delegate = self

        popController.popoverPresentationController?.sourceView = sender.plainView // button

        popController.popoverPresentationController?.sourceRect = sender.plainView.bounds

        // present the popover

        controller.present(popController, animatedtruecompletionnil)


    }


You can add the above function inside your viewcontroller and get the popoverviewcontroller as subview.
If you tap outside the popover it will be close.

Comments