3

Considering the following code, why the animations in the views that are initialized without the n property stops when you scroll the list?

Tested on Xcode 11.3 (11C29) with a new default project on device and simulator.

import SwiftUI

struct ContentView: View {
    var body: some View {

        HStack {
            List(1...50, id: \.self) { n in
                HStack {
                    KeepRolling()
                    Spacer()
                    KeepRolling(n: n)
                }
            }
        }

    }
}

struct KeepRolling: View {

    @State var isAnimating = false

    var n: Int? = nil

    var body: some View {

        Rectangle()
            .frame(width: 50, height: 50)
            .rotationEffect(Angle(degrees: self.isAnimating ? 360 : 0))
            .onAppear {
                withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) {
                    self.isAnimating = true
                }
            }

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

enter image description here

1 Answer 1

5

IMO it is due to caching/reuse in List. For List all the values of KeepRolling() is the same, so .onAppear is not always re-called.

If to make every such view unique, say using .id as below, all works (tested with Xcode 11.2)

KeepRolling().id(UUID().uuidString)
Sign up to request clarification or add additional context in comments.

1 Comment

Actually .onAppear is always being re-called for me but the caching/reuse thing seems to be the cause of the animation being ignored. The .id trick works but I would be careful with it because it may decrease the List performance. Thanks @Asperi !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.