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)
}
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.
Checkout the preferredContentSize property of UIViewController:
let height = yourDataArray.count * Int(popOverViewController.tableView.rowHeight)
popOverViewController.preferredContentSize = CGSize(width: 300, height: height)
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#>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With