【问题标题】:SwiftUI - Animation in view stops when scrolling the listSwiftUI - 滚动列表时视图中的动画停止
【发布时间】:2019-12-30 22:24:45
【问题描述】:

考虑下面的代码,为什么在没有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()
    }
}

【问题讨论】:

    标签: list animation scroll swiftui


    【解决方案1】:

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

    如果要使每个这样的视图都独一无二,比如使用.id,如下所示,一切正常(使用 Xcode 11.2 测试)

    KeepRolling().id(UUID().uuidString)
    

    【讨论】:

    • 实际上.onAppear 总是被我重新调用,但缓存/重用似乎是动画被忽略的原因。 .id 技巧有效,但我会小心使用它,因为它可能降低列表性能。谢谢@Asperi!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多