Home > Software engineering >  SwiftUI animation transition of conditional views
SwiftUI animation transition of conditional views

Time:08-26

So, i have this little app with a button where i can change the how the main view display its items, with a grid or list. But i would like to add a little animation when it makes its transition from one to another. I messed i little bit trying to add withAnimationon the button, or .transition() inside the views, but nothing seems to do the trick. Any tips on how can i achieve this?

struct FrameworkGridView: View {
    @StateObject var viewModel = FrameworkGridViewModel()
    @Binding var isGrid: Bool
    var body: some View {
        NavigationView {
            Group {
                if viewModel.isGrid {
                    ScrollView {
                        LazyVGrid(columns: viewModel.columns) {
                            ForEach(MockData.frameworks) { framework in
                                FrameworkTitleView(framework: framework, isGrid: $viewModel.isGrid)
                                    .onTapGesture {
                                        viewModel.selectedFramework = framework
                                    }
                            }
                        }
                    }
                    .sheet(isPresented: $viewModel.isShowingDetailView) {
                        DetailView(framework: viewModel.selectedFramework ?? MockData.sampleFramework, isShowingDetailView: $viewModel.isShowingDetailView, isGrid: $viewModel.isGrid)
                    }
                } else {
                    List {
                        ForEach(MockData.frameworks) { framework in
                            NavigationLink(destination: DetailView(framework: framework, isShowingDetailView: $viewModel.isShowingDetailView, isGrid: $viewModel.isGrid)) {       
                                FrameworkTitleView(framework: framework, isGrid: $viewModel.isGrid)
                            }
                        }
                    }
                }
            }
            .toolbar {
                Button {
                    viewModel.isGrid.toggle()
                } label: {
                    Image(systemName: viewModel.isGrid ? "list.dash" : "square.grid.2x2")
                }
                
            }
        }
        
    }
}

[enter image description here]

CodePudding user response:

I believe you're looking for matchedGeometryEffect. Check out WWDC 2020: What's New in SwiftUI starting around 19 minutes in. The SwiftUI Lab also has a couple of articles about it.

  • Related