SwiftUI: withAnimation and @AppStorage

Week 467 was posted by Charanjit Chana on 2026-10-11.

Experimenting over the past week with SwiftUI, I ran into an issue where toggling a boolean value wouldn't animate very well. I proved that it worked in a #Preview, but my app failed to animate an accordion style layout using a List and Sections.

@State var switchText: Bool = false

var body: some View {
    List {
        Section {
            if switchText {
                Text("123")
            }
        } header: {
            HStack {
                Text("My Section")
                Button {
                    withAnimation {
                        switchText.toggle()
                    }
                } label: {
                    Text("Switch the text")
                }
            }
        }
    }
}

This worked flawlessly, but it took me a while to realise that I wasn't using a @State value but @AppStorage instead.

This complicates the situation as the values are not updated in the same way. I didn't want to give up @AppStorage approach as I wanted values to persist between app usage so came up with a solution that toggles using @State in the view and then updates @AppStorage on the change of the value:

@State var localSwitchText: Bool = false
@AppStorage var switchText: Bool = false

var body: some View {
    List {
        Section {
            if localSwitchText {
                Text("123")
            }
        } header: {
            HStack {
                Text("My Section")
                Button {
                    withAnimation {
                        localSwitchText.toggle()
                    }
                } label: {
                    Text("Switch the text")
                }
            }
        }
    }
    .onAppear {
        localSwitchText = switchTest
    }
    .onChange(of: localSwitchText) {
        switchTest = localSwitchText
    }
}

Inside .onAppear, I assign the @AppStorage value to the localSwitchText variable so that it's original state is known and can be toggled. Whenever that value changes, it is stored in a correspending @AppStorage variable, in this case switchText.

It adds a bit of an overhead in state management but provides great animations in SwiftUI out of the box.


Tags: development, swiftui


Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like