How to do a “reveal”-style collapse/expand animation in SwiftUI?

Something like this might work. You can modify the height of what you want to disclose to be 0 when hidden or nil when not so that it’ll go for the height defined by the views. Make sure to clip the view afterwards so the contents are not visible outside of the frame’s height when not disclosed.

struct ContentView: View {
    @State private var isDisclosed = false
    
    var body: some View {
        VStack {
            Button("Expand") {
                withAnimation {
                    isDisclosed.toggle()
                }
            }
            .buttonStyle(.plain)
            
            
            VStack {
                GroupBox {
                    Text("Hi")
                }
                
                GroupBox {
                    Text("More details here")
                }
            }
            .frame(height: isDisclosed ? nil : 0, alignment: .top)
            .clipped()
            
            HStack {
                Text("Cancel")
                Spacer()
                Text("Book")
            }
        }
        .frame(maxWidth: .infinity)
        .background(.thinMaterial)
        .padding()
    }
}

No, this wasn’t trying to match your design, either. This was just to provide a sample way of creating the animation.

Leave a Comment