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

后端 未结 6 1097
情话喂你
情话喂你 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:24

    For swift 4 if you want to observe the content size I found this to be the optimal solution. Reporting it here since I did not find a complete example online:

    class MyTableViewController: UITableViewController {
    
        private var kvoContext = 0
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            addObserver(self, forKeyPath: #keyPath(tableView.contentSize), options: .new, context: &kvoContext)
    
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            removeObserver(self, forKeyPath: #keyPath(tableView.contentSize))
            super.viewDidDisappear(animated)
        }
    
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if context == &kvoContext, keyPath == #keyPath(tableView.contentSize),
                let contentSize = change?[NSKeyValueChangeKey.newKey] as? CGSize  {
                self.popoverPresentationController?.presentedViewController.preferredContentSize = contentSize
            }
        }
    }
    

提交回复
热议问题