gpt4 book ai didi

animation - SwiftUI:NavigationView中的显式动画损坏了吗?

转载 作者:行者123 更新时间:2023-12-03 14:36:45 33 4
gpt4 key购买 nike

当我在NavigationView中放置显式动画时,由于不希望有的副作用,它会为NavigationView内容的初始布局设置动画。对于无限动画,它尤其糟糕。有没有办法禁用这种副作用?
示例:下图假定是全屏蓝色背景上的红色动画加载器。相反,我得到了一个缩放蓝色背景的无限循环:
enter image description here

import SwiftUI

struct EscapingAnimationTest: View {
var body: some View {
NavigationView {
VStack {
Spacer()
EscapingAnimationTest_Inner()
Spacer()
}
.backgroundFill(Color.blue)
}
}
}

struct EscapingAnimationTest_Inner: View {
@State var degrees: CGFloat = 0

var body: some View {
Circle()
.trim(from: 0.0, to: 0.3)
.stroke(Color.red, lineWidth: 5)
.rotationEffect(Angle(degrees: degrees))
.onAppear() {
withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
degrees = 360
}
}
}
}

struct EscapingAnimationTest_Previews: PreviewProvider {
static var previews: some View {
EscapingAnimationTest()
}
}

最佳答案

这是固定的部分。已在Xcode 12/iOS 14上进行测试。
demo

struct EscapingAnimationTest_Inner: View {
@State var degrees: CGFloat = 0

var body: some View {
Circle()
.trim(from: 0.0, to: 0.3)
.stroke(Color.red, lineWidth: 5)
.rotationEffect(Angle(degrees: Double(degrees)))
.animation(Animation.linear(duration: 1).repeatForever(autoreverses: false), value: degrees)
.onAppear() {
DispatchQueue.main.async {
degrees = 360
}
}
}
}
更新:将使用 withAnimation
.onAppear() {
DispatchQueue.main.async {
withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
degrees = 360
}
}

}

关于animation - SwiftUI:NavigationView中的显式动画损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64566492/

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