Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Animation in view stops when scrolling the list

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

like image 679
JS1010111 Avatar asked Dec 08 '25 00:12

JS1010111


1 Answers

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)
like image 177
Asperi Avatar answered Dec 11 '25 00:12

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!