iosswiftuibarbuttonitemuipopover

UIBarButtonItem gives me wrong frame for popoverPresentationController


I have a toolbar with a UIBarButtomItem at the left corner with the label Admin

enter image description here

I need to show a popover when it taps it, but it appears in a wrong place, it appears at the top left of the screen:

enter image description here

This is the function to open the popover:

// this IBAction is assigned only to the Admin bar button item
@IBAction func openAdmin(sender: UIBarButtonItem) {
    let alertController = UIAlertController(title: nil, message: "Elige una opción", preferredStyle: .ActionSheet)

    // action button initializations... ... ...

    let barButtonItemSize = sender.valueForKey("view")

    alertController.popoverPresentationController?.sourceView = self.view
    alertController.popoverPresentationController?.sourceRect = barButtonItemSize!.frame

    presentViewController(alertController, animated: true, completion: nil)
}

Also I get this warning on the console when I touch the Admin bar button:

Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates

What am I doing wrong? or What do I need to do to present the popover at the top of the Admin?


Solution

  • Replace

    alertController.popoverPresentationController?.sourceView = self.view
    alertController.popoverPresentationController?.sourceRect = barButtonItemSize!.frame
    

    with

    alertController.popoverPresentationController?.sourceView = sender
    alertController.popoverPresentationController?.barButtonItem = sender