SwiftUI - 滚动列表时视图中的动画停止

JS1*_*111 3 animation scroll list swiftui

考虑以下代码,为什么在没有该属性的情况下初始化的视图中的动画n在滚动列表时停止?

在 Xcode 11.3 (11C29) 上使用设备和模拟器上的新默认项目进行了测试。

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Asp*_*eri 5

IMO 这是由于List. 由于List的所有值KeepRolling()都是相同的,因此.onAppear并不总是被重新调用。

如果要使每个此类视图都独一无二,请使用.id如下所示,所有作品都有效(使用 Xcode 11.2 进行测试)

KeepRolling().id(UUID().uuidString)
Run Code Online (Sandbox Code Playgroud)