首页 > 解决方案 > ScrollView 中的 SwiftUI 动画不起作用

问题描述

只是无法理解这一点。我有一个完美的简单动画。但是当我将视图包装到 ScrollView 中(通过取消注释 2 行)它不再动画了吗?任何人的线索?

import SwiftUI

struct ContentView: View {
    @State var offset = CGSize(width: 0, height: 0)

    var body: some View {
//      ScrollView {
            VStack(spacing: 50) {
                Rectangle()
                    .frame(width: 100, height: 100)
                    .offset(self.offset)
                Button(action: {
                    withAnimation {
                        self.offset.width += 66
                    }
                })
                {
                    Text("Animate me")
                }
            }.frame(width: 300)
//      }
    }
}

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

标签: iosswiftswiftuiios13

解决方案


我已经注意到了这种行为。问题似乎是明确的动画。如果您使用隐式动画,它可以工作:

struct ContentView: View {
    @State var offset = CGSize(width: 0, height: 0)

    var body: some View {
      ScrollView {
            VStack(spacing: 50) {
                Rectangle()
                    .frame(width: 100, height: 100)
                    .offset(self.offset)
                    .animation(.linear)
                Button(action: {
                    self.offset.width += 66
                })
                {
                    Text("Animate me")
                }
            }.frame(width: 300)
      }
    }
}

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

我还没有设法得到原因,所以将其视为一种解决方法。这可能是一个 SwiftUI 错误或我仍然无法理解的东西。


推荐阅读