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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.