Search code examples
iosswiftswiftuiswiftui-tabview

SwiftUI how to use .fixedSize() modifier with TabView to only take up the space it needs?


I have a TabView that is embeeded in a ZStack. My goal is to make the ZStack and it's child TabView to only take up the space needed to lay out the views inside the TabView. The .fixedSize() modifier accomplishes this if I change my TabView to a VStack but with a TabView it squishes the TabView too small. How can I accomplish my goal while still not obscuring the TabView's content?

enter image description here

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red
            
            TabView {
                VStack {
                    Text("One")
                    Text("One")
                    Text("One")
                }
                VStack {
                    Text("Two")
                    Text("Two")
                    Text("Two")
                }
                VStack {
                    Text("Three")
                    Text("Three")
                    Text("Three")
                }
            }
            .tabViewStyle(.page)
            
        }
        
        .fixedSize() //why doesn't this work as expected?
        
    }
}

Solution

  • I had the same problem, for me this did the trick without hardcoding it:

    TabView(){
    ....
    }
    .aspectRatio(1, contentMode: .fit)
    .frame(maxWidth: .infinity)