0:00
/
0:00

💡 SwiftUI FYI #3 - Transitions

A cool slide-in and scale-out example 😎💨

SwiftUI transitions offer elegant and polished insertion and removal of views, with incredible customization options.

Available transitions include .opacity, .scale, .slide, .move, .asymmetric, .blurReplace, and more.
Experiment to find the best fit for your use case.

📌 Remember to toggle showDetail within an animation block for the transition to work.

FYI Tip 💡: The .transition modifier animates view insertion and removal, while .animation animates view properties.

Full code below!

🤝 Find more about me on saidmarouf.com. I’m also on XThreads, and LinkedIn

Thanks for reading Your Weekly SwiftUI FYI 💡! Subscribe for free to receive new posts and support my work.


import SwiftUI

struct TransitionExamples: View {
    
    @State private var showDetail = false
    
    var body: some View {
        VStack(spacing: 24) {
            
            Button {
                withAnimation(.spring(duration: 0.4, bounce: 0.35,
                                       blendDuration: 0.8)) {
                    showDetail.toggle()
                }
            } label: {
                Label("Toggle Message", systemImage: "tray.fill")
                    .font(.title)
                    .padding(.horizontal, 16)
            }
            .buttonStyle(.borderedProminent)
            
            if showDetail {
                let transition = AsymmetricTransition(
                    insertion: .slide.combined(with: .opacity),
                    removal: .scale(0, anchor: .bottom)
                               .combined(with: .opacity)
                )
                
                MessageView().transition(transition)
            }
        }
    }
}


struct MessageView: View {
    var body: some View {
        VStack {
            Text("You have a new Message from **Said**!")
                .font(.title)
                .foregroundStyle(.black)
                .multilineTextAlignment(.center)
                .padding()
        }
        .background(Color.teal.gradient)
        .cornerRadius(16)
    }
}

#Preview {
    TransitionExamples()
}

Discussion about this video

User's avatar