lewis
lewis

Reputation: 3172

SwiftUI: Animate View properties in response to Toggle change

I'm trying to change a view in response to changing a Toggle. I figure out a way to do it as long as I mirror the state value the toggle is using.

Is there a way to do it without creating another variable?

Here's my code. You can see that there are three animations triggered.

import SwiftUI

struct OverlayView: View {
    
    @State var toggle: Bool = false
    @State var animatedToggle: Bool = false
    
    var body: some View {
        
        VStack {
            Image(systemName: "figure.arms.open")
                .resizable()
                .scaledToFit()
                .foregroundColor(animatedToggle ? .green : .red) // << animated
                .opacity(animatedToggle ? 1 : 0.2) // << animated
            
            if animatedToggle { // << animated
                Spacer()
            }
            
            Toggle("Overlay", isOn: $toggle)
                .onChange(of: toggle) { newValue in
                    withAnimation {
                        animatedToggle = toggle
                    }
                }
        }
    }
}

Upvotes: 0

Views: 293

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29252

Just use the .animation view modifier

.animation(.default, value: toggle)

Then remove the second variable

struct OverlayView: View {
    @State var toggle: Bool = false
    var body: some View {
        
        VStack {
            Image(systemName: "figure.arms.open")
                .resizable()
                .scaledToFit()
                .foregroundColor(toggle ? .green : .red)
                .opacity(toggle ? 1 : 0.2)
            
            if toggle {
                Spacer()
            }
            
            Toggle("Overlay", isOn: $toggle)

        }.animation(.default, value: toggle)

    }
}

Upvotes: 1

Related Questions