在 SwiftUI 图像上重复动画

fuz*_*uzz 15 xcode swift swiftui

鉴于以下情况struct

struct PeopleList : View {
    @State var angle: Double = 0.0
    @State var isAnimating = true

    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever()
    }

    var body: some View {
        Button(action: {}, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? self.angle : 0.0))
                .onAppear {
                    withAnimation(self.foreverAnimation) {
                        self.angle += 10.0
                    }
                }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它Image会顺时针旋转并重复直到self.isAnimating是,false尽管它只动画一次。

Asp*_*eri 21

这是在出现和开始/停止时连续进行的可能解决方案。使用 Xcode 11.4 / iOS 13.4 测试。

演示

struct PeopleList : View {
    @State private var isAnimating = false
    @State private var showProgress = false
    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever(autoreverses: false)
    }

    var body: some View {
        Button(action: { self.showProgress.toggle() }, label: {
            if showProgress {
                Image(systemName: "arrow.2.circlepath")
                    .rotationEffect(Angle(degrees: self.isAnimating ? 360 : 0.0))
                    .animation(self.isAnimating ? foreverAnimation : .default)
                    .onAppear { self.isAnimating = true }
                    .onDisappear { self.isAnimating = false }
            } else {
                Image(systemName: "arrow.2.circlepath")
            }
        })
        .onAppear { self.showProgress = true }
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_* T. 10

更新:停止动画时涉及回旋,解决方案已解决。

我认为这就是您正在寻找的:

struct PeopleList : View {
    @State var angle: Double = 0.0
    @State var isAnimating = false
    
    var foreverAnimation: Animation {
        Animation.linear(duration: 2.0)
            .repeatForever(autoreverses: false)
    }
    
    var body: some View {
        Button(action: {}, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? 360.0 : 0.0))
                .animation(self.foreverAnimation)
                .onAppear {
                    self.isAnimating = true
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来我们必须以某种方式摆脱“repeatForever”动画,就像这样 .animation(self.isAnimating ?foreverAnimation :foreverAnimationNo)。foreverAnimationNo 将是一个不重复的动画。 (4认同)