Swift iPad - How to present a formSheet with custom size based on a table view content?

Viewed 20

In my app i present a form sheet in this way for iPad devices:

myViewController = .formSheet
present(myViewController, animated: true)

This ViewController is very simple: there is just a table view displaying n elements.

My goal is make the formSheet size the same as the table view with its n elements.

I actually achieved that with this code:

class MyViewControlller: UIViewController {
    
    @IBOutlet weak var myTable: UITableView!
  
    private var observer: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()
        myTable.delegate = self
        myTable.dataSource = self
        
        observer = myTable(\.contentSize, options: [.new], changeHandler: { [weak self] (table, _) in
            guard let self = self else {
                return
            }
            self.preferredContentSize = CGSize(width: table.contentSize.width, height: table.contentSize.height + 30.0)
            self.view.layoutIfNeeded()
            
        })
    } 
}

But the problem is that while presenting the formSheet (while it is sliding from bottom to the center of the screen) I can clearly see an animation where the bottom of the sheet is adjusting its size until it reaches the center of the screen.

What I'm trying to achieve is this: When the sheet starts sliding from the bottom to the center of the screen it already has the right dimensions.

Am I doing something wrong with the code?

0 Answers
Related