ScrollView 中的 SwiftUI 动画不起作用
SwiftUI animation within ScrollView not working
我实在想不通。我有一个简单的动画,效果很好。但是,当我将视图包装到 ScrollView 中(通过取消注释这两行)时,它不再具有动画效果了吗?有人有线索吗?
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()
}
}
我已经注意到了这种行为。问题似乎是显式动画。如果您选择隐式动画,它会起作用:
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 的错误或我仍然无法理解的东西。
我实在想不通。我有一个简单的动画,效果很好。但是,当我将视图包装到 ScrollView 中(通过取消注释这两行)时,它不再具有动画效果了吗?有人有线索吗?
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()
}
}
我已经注意到了这种行为。问题似乎是显式动画。如果您选择隐式动画,它会起作用:
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 的错误或我仍然无法理解的东西。