GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

A TabView inside a list?

Forums > SwiftUI

I have a List section whose contents change if a button is pressed. Currently, the animation slides the view to the right, but I would like it to slide right for one transition and left for the other. My idea was to put the section inside a TabView (with page style), which has this behavior. However, when displaying a TabView inside a List, the TabView is scrunched vertically.

Is there any way to get this to display properly, or is there another option I haven't considered? Example code:

struct ContentView: View {

  @State private var pageToggle = false

  var page1: some View {
    VStack {
      Text("One")
      Text("Two")
      Text("Three")
    }
  }

  var page2: some View {
    VStack {
      Text("Four")
      Text("Five")
      Text("Six")
    }
  }

  var body: some View {
    List {
      Button("Toggle Page") {
        withAnimation {
          pageToggle.toggle()
        }
      }

      Section(header: Text("Page View")) {
        TabView(selection: $pageToggle) {
          page1
            .tag(false)
          page2
            .tag(true)
        }
        .tabViewStyle(PageTabViewStyle())
      }
    }
    .listStyle(InsetGroupedListStyle())
  }
}

The animation is correct, but the view isn't displayed properly.

3      

You can add a frame modifier to the TabView.

Use .frame(height:) for a fixed height, or use .frame(minHeight:maxHeight:) so the TabView adapts to its content's size.

3      

How would I programmatically determine the ideal height of the frame?

3      

You can use this modifier on the TabView to make it show at its ideal height.

.fixedSize(horizontal: false, vertical: true)

I would add some padding above and below the content so that it's not pushed against the edges.

You will have to set the indexDisplayMode parameter of PageTabViewStyle to .never so that the paging dots don't interfere with the content.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.