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

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

    Simple dynamic answer for Swift 4.x and Swift 5.x involving no size-computation (modern version of Bo Frese answer):

    private var contentSizeObserver : NSKeyValueObservation?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        contentSizeObserver = tableView.observe(\.contentSize) { [weak self] tableView, _ in
            self?.preferredContentSize = CGSize(width: 320, height: tableView.contentSize.height) // Here I fixed the width but you can do whatever you want
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    
        contentSizeObserver?.invalidate()
        contentSizeObserver = nil
    }
    

提交回复
热议问题