Search code examples
iospopupwindowuistoryboardsegue

How to present popUp when user taps on right bar button item?


I'm relatively new at iOS. I'm struggling, for a while now with this issue. I don't know how to set the logic for presenting popUp when user taps on right bar button item. Basically, it should look like this:PopUp I searched through Google, but I didn't have any luck. I would appreciate if someone would help me with some code.

//My VC

     override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(clickShare))
        rightBarButtonItem.tintColor = UIColor.black
        navigationItem.rightBarButtonItem = rightBarButtonItem
   //     navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: UIBarButtonItemStyle.plain, target: self, action: #selector(clickShare))
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "backArrow"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(goBack))
        UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font : UIFont(name: "OpenSans", size: 14)! ], for: .normal)

    }

    //MARK: - Actions
   @objc func goBack() {
        navigationController?.popViewController(animated: true)
    }


    @objc func clickShare() {

    //this is where the logic should go
    }

//This is my storyboard: Storyboard


Solution

  • Add following action,

    @IBAction func yourButtonClickAction(sender: UIBarButtonItem) {
        let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("YourViewController") as! UIViewController
        vc.modalPresentationStyle = UIModalPresentationStyle.Popover
        let popover: UIPopoverPresentationController = vc.popoverPresentationController!
        popover.barButtonItem = sender
        popover.delegate = self
        presentViewController(vc, animated: true, completion:nil)
    }
    

    Add this action to you barButtonItem.
    'YourViewController' = controller consisting of Public, followers options.