UIPopover presentFromBarButton off center UIPopover presentFromBarButton off center ios ios

UIPopover presentFromBarButton off center


Here's one way to do this: Instead of using a UIBarButtonSystemItem, use a UIBarButtonItem with a custom view. Just drag a UIButton into the UINavigationBar to get a UIBarButtonItem with an embedded UIButton, which shows up as the UIBarButtonItem's customView.

@IBAction func didTapActionButton(_ sender: Any) {    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "myPopover") {        vc.modalPresentationStyle = .popover        guard let innerView = actionButton.customView else {            // Unexpected missing custom view            return        }        vc.popoverPresentationController?.sourceView = navigationController?.navigationBar        vc.popoverPresentationController?.sourceRect = innerView.frame        self.present(vc, animated: true, completion: nil)    }}


You must specify the frame of the bar button from which the pop over needs to be presented.

The following code presents a UIAlertController as a popover from a bar button.

    @IBOutlet weak var playerRightBarButton: UIBarButtonItem!    extension UIBarButtonItem {       var frame: CGRect? {        guard let view = self.value(forKey: "view") as? UIView else {          return nil      }      return view.frame    }  }    let alert = UIAlertController(title: "", message: "Sample PopOver",     preferredStyle: .actionSheet)    if alert.responds(to: #selector(getter: popoverPresentationController)) {            alert.popoverPresentationController?.sourceView = self.view            alert.popoverPresentationController?.barButtonItem = playerRightBarButton            alert.popoverPresentationController?.permittedArrowDirections = .up            if let frame = playerRightBarButton.frame {                alert.popoverPresentationController?.sourceRect = frame            }        }        self.present(alert, animated: true, completion: nil)