Search code examples
swiftxcodeswift3popover

How center popover on TableView?


I'm make a tableview with a button in every cell, when you push the button shows a popover, but the problem is a make the popover to center over the tableview, but if you go down the tableView, and push the button the popover use as guideline the select button, so the popover go up. On the next images you can see what I trying to explain.

enter image description here

The code used when you press the button from the cell:

func buttonPressed(sender: UIButton){

    let buttonTag = sender.tag

    let width = self.view.frame.midX + (self.view.frame.midX/2)

    let height = info[buttonTag].nota.calculateHeight(width: width, sizeFont: 16.0) + 40

    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let vc = storyboard.instantiateViewController(withIdentifier: "NotaTable") as! Popever

    vc.modalPresentationStyle = UIModalPresentationStyle.popover
    vc.popoverPresentationController?.delegate = self
    vc.preferredContentSize = CGSize(width: width, height: height + 115)
    vc.width = width

    let popover: UIPopoverPresentationController = vc.popoverPresentationController!
    popover.delegate = self
    popover.sourceView = self.view

    popover.sourceRect = CGRect(x: self.view.frame.midX - (width/2), y: self.view.frame.midY - (height/2), width: width, height: height)

    popover.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

    present(vc, animated: true, completion:nil)

}

So, How do I make the popover to focus on center no matter what button press?

Thanks advance!


Solution

  • I find the way to solve this, changing the popover.sourceRect, instead of completing de x and y position with self.view.frame replaced for self.view.bounds

    let popover: UIPopoverPresentationController = vc.popoverPresentationController!
        popover.delegate = self
        popover.sourceView = self.view
    
        popover.sourceRect = CGRect(x: (self.view.bounds.midX - (width/2)), y: (self.view.bounds.midY - (height/2)), width: width, height: height)
    

    Here I leave you the difference between frame and bounds:

    The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

    The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

    I got it from here