Search code examples
swiftuiswiftui-tabview

How to dynamically tighten height for TabView?


The TabView seems to stretch to its maximum height, but I'd like it to shorten to height as much as it requires instead of empty space. This is what it looks like even tho there are Spacer views around it:

enter image description here

struct ContentView: View {
    var body: some View {
        Text("Some text")
        Text("Some text")
        Text("Some text")
        Spacer()
        TabView {
            GroupBox(label: Text("This is the title 1")) {
                Label("Some item 1", systemImage: "checkmark.circle.fill")
                Label("Some item 2", systemImage: "checkmark.circle.fill")
                Label("Some item 3", systemImage: "checkmark.circle.fill")
                Label("Some item 4", systemImage: "checkmark.circle.fill")
            }
            .padding()
            GroupBox(label: Text("This is the title 2")) {
                Label("Some item 1", systemImage: "checkmark.circle.fill")
                Label("Some item 2", systemImage: "checkmark.circle.fill")
                Label("Some item 3", systemImage: "checkmark.circle.fill")
                Label("Some item 4", systemImage: "checkmark.circle.fill")
            }
            .padding()
            GroupBox(label: Text("This is the title 3")) {
                Label("Some item 1", systemImage: "checkmark.circle.fill")
                Label("Some item 2", systemImage: "checkmark.circle.fill")
                Label("Some item 3", systemImage: "checkmark.circle.fill")
                Label("Some item 4", systemImage: "checkmark.circle.fill")
            }
            .padding()
        }
        .tabViewStyle(PageTabViewStyle())
        .background(Color.yellow)
        Spacer()
        Text("Some text")
        Text("Some text")
        Text("Some text")
    }
}

Is there a way to dynamically tighten the height to what's needed by its children?


Solution

  • Use .frame( height: .leastNormalMagnitude)

    .tabViewStyle(PageTabViewStyle())
    .background(Color.yellow)
    .frame( height: .leastNormalMagnitude)
    

    The Page Index covers the views. You probably need to give GroupBoxes a 40-50 points padding bottom or change indexViewStyle's background.

     .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))