Dynamic height SwiftUI UIViewControllerRepresentable

Viewed 351

I have a UITableViewController in my SwiftUI project. The number of cells in the UITableView can be different. 1 cellHeight is 60. If I don't set a .frame(height ) on the Section it will barely show one full cell. But since I don't know how many rows there will be I can't set the .frame(height). And setting minHeight/maxHeight will always use the maxHeight...

Is there someway to count the height according to the number of cells or can I make the TableView() frame dynamic in some other way?

var body: some View {
        NavigationView {
            Form {
                Section(header: Text("My UIKit Table View")) { TableView() }
                Section(header: Text("My SwiftUI View")) { ContentView() }
            }
        }
    }
1 Answers

You can use .environment(\.defaultMinListRowHeight, CGFloat) on your Form{} and then calculate the Height based on the Itemcount.

Example:

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("My UIKit Table View")) { TableView() }
            Section(header: Text("My SwiftUI View")) { ContentView() }
        }
        .environment(\.defaultMinListRowHeight, 40)
        .frame(height: (50 * TableViewCount) + (50 * ContentViewCount)) + 50 * SectionHeaderCount)
    }
}

This has to be further customized. In my example the listRowHeight is 40, but I calculate the height with 50 so the Dividers and some Spacing is accounted for correctly. Additionally I add 50 for the header space of the Sections.

This is kindof a hacky solution (like many in SwiftUI), but once properly Setup it works surprisingly well.

Related