In SwiftUI, how do I morph 2 glass buttons besides in each other when interacting with one. Give a code example.

Asked on 2025-09-12

1 search

To morph two glass buttons in SwiftUI when interacting with one, you can use the new Liquid Glass effect introduced in the WWDC 2025 sessions. The Liquid Glass effect allows for fluid morphing transitions between UI elements, creating a seamless and dynamic user experience.

Here's a basic example of how you might achieve this using SwiftUI:

import SwiftUI

struct ContentView: View {
    @Namespace private var glassNamespace
    @State private var isExpanded = false

    var body: some View {
        VStack {
            if isExpanded {
                Button(action: {
                    withAnimation {
                        isExpanded.toggle()
                    }
                }) {
                    Text("Button 1")
                        .padding()
                        .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10))
                        .matchedGeometryEffect(id: "glassEffect", in: glassNamespace)
                }
            } else {
                Button(action: {
                    withAnimation {
                        isExpanded.toggle()
                    }
                }) {
                    Text("Button 2")
                        .padding()
                        .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10))
                        .matchedGeometryEffect(id: "glassEffect", in: glassNamespace)
                }
            }
        }
    }
}

Explanation:

  1. Namespace: A @Namespace is declared to allow for matched geometry effects, which are used to create smooth transitions between views.

  2. State: A @State variable isExpanded is used to toggle between the two button states.

  3. Matched Geometry Effect: The matchedGeometryEffect modifier is applied to both buttons with the same id and namespace. This allows SwiftUI to animate the transition between the two views smoothly.

  4. Animation: The withAnimation block is used to animate the state change, which triggers the morphing effect.

This example demonstrates how to use the Liquid Glass effect to create a morphing transition between two buttons. For more detailed information, you can refer to the session Build a SwiftUI app with the new design (17:57) from WWDC 2025.