gpt4 book ai didi

animation - swiftui,动画应用于父效果子动画

转载 作者:行者123 更新时间:2023-12-03 23:01:16 25 4
gpt4 key购买 nike

RectangleView 有滑动动画,他的子 TextView 有旋转动画。我想 RectangleView 和他的 child (TextView)作为一个整体滑入屏幕(easeInOut)当 Go!按下,TextView 永远旋转(线性)。但实际上,子TextView与其父分离,旋转(线性)和滑动(线性),并且永远重复。
为什么动画应用于父效果子动画?

struct AnimationTestView: View {
@State private var go = false
var body: some View {
VStack {
Button("Go!") {
go.toggle()
}
if go {
RectangleView()
.transition(.slide)
.animation(.easeInOut)
}
}.navigationTitle("Animation Test")
}
}

struct RectangleView: View {
var body: some View {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.pink)
.overlay(TextView())
}
}

struct TextView: View {
@State private var animationRotating: Bool = false
let animation = Animation.linear(duration: 3.0).repeatForever(autoreverses: false)

var body: some View {
Text("Test")
.foregroundColor(.blue)
.rotationEffect(.degrees(animationRotating ? 360 : 0))
.animation(animation)
.onAppear { animationRotating = true }
.onDisappear { animationRotating = false }
}
}

最佳答案

如果有多个同步动画,通用解决方案(在大多数情况下)是为每个动画使用显式状态值。
所以这是一个更正的代码(使用 Xcode 12.1/iOS 14.1 测试,使用模拟器或设备,预览会错误地呈现一些过渡)
demo

struct AnimationTestView: View {
@State private var go = false
var body: some View {
VStack {
Button("Go!") {
go.toggle()
}
VStack { // container needed for correct transition !!
if go {
RectangleView()
.transition(.slide)
}
}.animation(.easeInOut, value: go) // << here !!
}.navigationTitle("Animation Test")
}
}

struct RectangleView: View {
var body: some View {
Rectangle()
.frame(width: 100, height: 100)
.foregroundColor(.pink)
.overlay(TextView())
}
}

struct TextView: View {
@State private var animationRotating: Bool = false
let animation = Animation.linear(duration: 3.0).repeatForever(autoreverses: false)

var body: some View {
Text("Test")
.foregroundColor(.blue)
.rotationEffect(.degrees(animationRotating ? 360 : 0))
.animation(animation, value: animationRotating) // << here !!
.onAppear { animationRotating = true }
.onDisappear { animationRotating = false }
}
}

关于animation - swiftui,动画应用于父效果子动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65582121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com