How do I adjust my popover to the size of the content in my tableview in swift?

Henny Lee picture Henny Lee · Apr 4, 2015 · Viewed 30.7k times · Source

I'm using popoverPresentationController to show my popover. The UITableViewController used to show as popover is created programmatically and will usually contain 1 to 5 rows. How do I set up this popover to adjust the size to the content of the tableview?

Code for my popover:

if recognizer.state == .Began {
    let translation = recognizer.locationInView(view)

    // Create popoverViewController
    var popoverViewController = UITableViewController()
    popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
    popoverViewController.tableView.backgroundColor = UIColor.popupColor()

    // Settings for the popover
    let popover = popoverViewController.popoverPresentationController!
    popover.delegate = self
    popover.sourceView = self.view
    popover.sourceRect = CGRect(x: translation.x, y: translation.y, width: 0, height: 0)
    popover.backgroundColor = UIColor.popupColor()

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

Answer

Bo Frese picture Bo Frese · Nov 27, 2016

In your UITableViewController's viewDidLoad() you can add an observer:

self.tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

Then add this method:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    self.preferredContentSize = tableView.contentSize
}

Lastly, in viewDidDisappear(), make sure you remove the observer:

tableView.removeObserver(self, forKeyPath: "contentSize")

This way the popover will automatically adjust size to fit the content, whenever it is loaded, or changed.