Home > database >  Replace .animation(.default) with withAnimation or .animation(.default, value)
Replace .animation(.default) with withAnimation or .animation(.default, value)

Time:08-31

I'm using a ScrollView to display information in a FAQ style. Inside the ScrollView, I open three custom made views. My problem is that these views are not animated. I already tried using the .animation(.default, value: xxx) using a Binding var with the FAQListView, but this doesn't work.

The animation works fine using the old .animation(.default), but I'd like to get rid of the warning. So, how can I replace the old one with the new ones?

The FAQListView shows an header text. By tapping on it, a more detailed description will appear to the bottom of the header.

struct FAQListView: View {
    let header: Text
    let content: Text
    @State public var collapsed = true
    
    var body: some View {
        VStack {
            HStack {
                header
                    .font(.headline)
                Spacer()
                Image(systemName: "chevron.forward")
                        .rotationEffect(.degrees(collapsed ? 0 : 90))
                        .animation(.linear, value: collapsed)
                        .foregroundColor(.blue)
            }
            .padding(.bottom, 10)
                
            if !collapsed {
                HStack {
                    content
                    Spacer()
                }
            }
                
        }
        .onTapGesture {
            collapsed.toggle()
        }
        .animation(.default, value: collapsed)
        .padding(20)
    }
}

struct FAQView: View {
    @Binding var dismiss: Bool
    var body: some View {
        NavigationView {
            ScrollView {
                FAQListView(header: Text("missingValuesHeader"), content: Text("missingValuesDesc"))
                FAQListView(header: Text("cannotImportFileHeader"), content: Text("cannotOpenFileDesc"))
                FAQListView(header: Text("logfileMissingHeader"), content: Text("logfileMissingDesc"))
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle(Text("FAQ"))
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("close") {
                        dismiss.toggle()
                    }
                }
            }
        }
    }
}

CodePudding user response:

Your animation should happen when collapsed is changed. Wrap collapsed.toggle() with withAnimation { } :

.onTapGesture {
    withAnimation {
        collapsed.toggle()
    }
}

You can control the type and speed of the animation by passing an animation value. For a very slow animation, for example:

.onTapGesture {
    withAnimation(.easeIn(duration: 2)) {
        collapsed.toggle()
    }
}
  • Related