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

后端 未结 6 1101
情话喂你
情话喂你 2021-01-31 03:17

I\'m using popoverPresentationController to show my popover. The UITableViewController used to show as popover is created programmatically and will usu

6条回答
  •  野的像风
    2021-01-31 03:28

    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.

提交回复
热议问题