Popover in iOS not displayed near or relative to a button

74 Views Asked by At

I am trying to display a popOver next/relative to a UIButton. My current popOver always defaults to the top left corner. Even tried setting sourceRect, sourceView but still it makes no difference. Any idea what else can cause this?

lazy var launchButton: UIButton = {
    let button = UIButton(frame: CGRect(x: 150, y: 200, width: 100, height: 50))
    button.setTitle("Launch", for: .normal)
    button.addTarget(self, action:#selector(launchPopOver), for: .touchUpInside)
    return button
}()

@objc func launchPopOver() {
     let pop = PopViewController() 
     pop.modalPresentationStyle = .popover
     pop.preferredContentSize.height = 250

    if let popPresentation = pop.popoverPresentationController {
       popPresentation.sourceView = launchButton
       popPresentation.sourceRect = launchButton.bounds
    }

    present(pop, animated: true, completion: nil)
}

override func viewDidLoad() {
  super.viewDidLoad()
  self.view.addSubView(launchButton)
}

class PopViewController: UIViewController, UIPopoverPresentationControllerDelegate {
 //
 public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
      return .none
 }
}
1

There are 1 best solutions below

4
radeknovis On

My first guess is that you shouldn't be using launchButton.bounds but launchButton.frame instead for the sourceRect value as bounds will typically resolve to having position of { x: 0, y: 0 } which would explain the

"always defaults to the top left corner"

For more details you can read this article https://programmingwithswift.com/difference-between-frame-and-bounds-in-swift/