Present a popover from an arbitrary anchor point in Swift

前端 未结 3 762
旧时难觅i
旧时难觅i 2020-12-13 22:57

I know how to present a popover from a bar button item as is described in this answer (for both iPhone and iPad).

I would like to add a popover for an arbit

3条回答
  •  暖寄归人
    2020-12-13 23:18

    Updated for Swift 3

    In the storyboard, add a view controller that you would like to be the popover. Set the Storyboard ID to be "popoverId".

    Also add a button to your main view controller and hook up the IBAction to the following code.

    import UIKit
    class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    
        @IBAction func buttonTap(sender: UIButton) {
    
            // get a reference to the view controller for the popover
            let popController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popoverId")
    
            // set the presentation style
            popController.modalPresentationStyle = UIModalPresentationStyle.popover
    
            // set up the popover presentation controller
            popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
            popController.popoverPresentationController?.delegate = self
            popController.popoverPresentationController?.sourceView = sender // button
            popController.popoverPresentationController?.sourceRect = sender.bounds
    
            // present the popover
            self.present(popController, animated: true, completion: nil)
        }
    
        // UIPopoverPresentationControllerDelegate method
        func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
            // Force popover style
            return UIModalPresentationStyle.none
        }
    }
    

    Setting the sourceView and sourceRect is what allows you to choose an arbitrary point to display the popover.

    That's it. Now it should like something like this when the button is tapped.

    Thanks to this article for help.

提交回复
热议问题