โœจtransition โŸฉ scale

โฌ†๏ธ ้œ€่ฆ๏ผš .show(if:)

๐Ÿ“— ๅƒ่€ƒ๏ผšMastering SwiftUI, Ch. 9: Animations & Transitions

struct ContentView: View {
    
    // โญ๏ธ 1. view state for showing/hiding
    @State private var show = false
    
    var body: some View {
        HStack {
            card("Show details", .green)
            card("Here is the details", .purple)
                // โญ๏ธ 2-1. the transition 
                //    should be associated with an animation, won't work on its own.
                .transition(.scale(scale: 0.01, anchor: .trailing))
                // โญ๏ธ 3. insert/remove the view
                .show(if: show)                    // ๐ŸŒ€ View + .show(if:)
        }
        // โญ๏ธ 4. event to trigger the insertion/removal
        .onTapGesture { 
            // โญ๏ธ 2-2. associated animation
            withAnimation(.spring()) { show.toggle() }
        }
        .padding(8)
        .border(.secondary)
    }
    
    /// card with text
    func card(_ text: String, _ color: Color) -> some View {
        RoundedRectangle(cornerRadius: 10)
            .frame(width: 200, height: 150) 
            .foregroundColor(color) 
            .overlay(
                Text(text)
                    .font(.system(.title, design: .rounded))
                    .bold()
                    .foregroundColor(.white)
                    .padding()
            )
    }
}

Last updated