UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

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.