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
}
}
My first guess is that you shouldn't be using
launchButton.boundsbutlaunchButton.frameinstead for thesourceRectvalue as bounds will typically resolve to having position of{ x: 0, y: 0 }which would explain theFor more details you can read this article https://programmingwithswift.com/difference-between-frame-and-bounds-in-swift/