Showing pop over from Bar Button in Navigation bar in iPhone

4.8k views Asked by At

In Swift, I'm trying to show a popover from a bar button item present in the top right position of navigation bar. Below is my code:

func showOptions(sender: UIBarButtonItem) {
    let optionsVC = OptionsViewController(nibName: "OptionsViewController", bundle: nil)
    optionsVC.delegate = self
    optionsVC.modalPresentationStyle = .popover
    optionsVC.preferredContentSize = CGSize(width: 200, height: 200)

    present(optionsVC, animated: true, completion: nil)

    let popController = optionsVC.popoverPresentationController
    popController?.permittedArrowDirections = .up
    popController?.delegate = self
    popController?.barButtonItem = sender
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    return .none
}

Its working good in iPad and not in iPhone. I've gone through the documentation and different web pages. Everything seems to be right. What's missing in my code?

1

There are 1 answers

0
Hamza Ansari On BEST ANSWER

The only problem here is you are presenting OptionsViewController before setting its popover delegate. So first set its delegate then call present function.

let popController = optionsVC.popoverPresentationController
popController?.permittedArrowDirections = .up
popController?.delegate = self
popController?.barButtonItem = sender

present(optionsVC, animated: true, completion: nil)