Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
}
like image 441
Henny Lee Avatar asked Apr 04 '15 18:04

Henny Lee


3 Answers

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.

like image 190
Bo Frese Avatar answered Oct 18 '22 08:10

Bo Frese


Checkout the preferredContentSize property of UIViewController:

let height = yourDataArray.count * Int(popOverViewController.tableView.rowHeight)
popOverViewController.preferredContentSize = CGSize(width: 300, height: height)
like image 30
zisoft Avatar answered Oct 18 '22 07:10

zisoft


Override the preferredContentSize property in your extension of the uitableviewcontroller as following:

override var preferredContentSize: CGSize {
    get {
        let height = calculate the height here....
        return CGSize(width: super.preferredContentSize.width, height: height)
    }
    set { super.preferredContentSize = newValue }
}

For calculating the height check out tableView.rectForSection(<#section: Int#>)

like image 21
Philip De Vries Avatar answered Oct 18 '22 06:10

Philip De Vries