简体   繁体   中英

How to calculate UIViewController's intrinsic content height?

I need to identify height of UIViewController in order to show it inside bottom sheet. For creating bottom sheet, I use FitterSheets library. It accepts UIViewController that I want to display inside sheet and some height. Then, the library displays my view controller with the height I specified. It seems everything ok and makes sense, but how am I able to calculate height of my view controller? It can be dynamic (for instance, dynamic views inside stackview). I cannot calculate its height before displaying it. In other words, I don't know how what will be the size of the content in my screen, because I take that data from the server. If you didn't understand problem, here is snipped of code:

present(SheetViewController(myViewController, size: ?), animated: false); 

What size I should pass there? Of course I can calculate it approximately (for instance, according to data I get from API, I can multiply the amount of data to height of some view in my screen). But, it will be approximately, not accurate.

I think my solution should be following: I don't specify any height when presenting SheetViewController . I just resize SheetViewController after my view controller's view is appeared fully. Pseudo code will be following:

override viewDidAppear(_ animated: Bool) {
       super.viewDidAppear(animated)
       var contentSize = 0 
       view.subviews.forEach {
           contentSize += $0.frame.height
       }
       sheetViewController?.resize(contentSize); 
}

But I don't think it is right solution and it actually does not work. So, what is the best way to solve my problem? How to display bottom sheet with the height equals to the height of the content?

Following what is explained in the library documentation:

If the view controller is smaller than the sizes specified, it will only grow as large as the intrensic height of the presented view controller. If it is larger, it will stop at each height specified in the initializer or setSizes function.

So you can remove the code you have in the viewDidAppear and just adding an array of sizes, where the first size is the one that determines the initial size of the sheet, for example:

present(SheetViewController(myViewController, sizes: [.fixed(100), .fullScreen]), animated: false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM