Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating Bindings in SwiftUI

I have the following code which partially shows or hides the Test view depending on a Binding<Bool>. I can wrap the testVisible.toggle() call in a withAnimation, however, ideally I would like to ensure that visible binding is always animated, even when called without a withAnimation. How can I make sure that whenever visible binding is changed, the change is animated?

struct ContentView: View {
    @State var testVisible: Bool = true
    
    var body: some View {
        ZStack {
            Color.white
                .onTapGesture {
                    testVisible.toggle()
                }
            
            Test(visible: $testVisible)
        }
            
    }
}

struct Test: View {
    @Binding var visible: Bool
    
    var body: some View {
        Text("Test")
            .opacity(visible ? 0.5 : 0)
    }
}
like image 977
BenJacob Avatar asked Oct 18 '25 22:10

BenJacob


1 Answers

Add a .animation() modifier to the Text view:

struct Test: View {
    @Binding var visible: Bool
    
    var body: some View {
        Text("Test")
            .opacity(visible ? 0.5 : 0)
            .animation(.linear(duration: 0.5))
    }
}
like image 117
vacawama Avatar answered Oct 21 '25 11:10

vacawama