在SwiftUI图像上重复动画

时间:2019-10-10 04:50:39

标签: swift xcode 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: {
            self.peopleViewModel.load()
        }, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? self.angle : 0.0))
                .onAppear {
                    withAnimation(self.foreverAnimation) {
                        self.angle += 10.0
                    }
                }
        })
    }
}

我希望Image可以顺时针旋转并重复执行,直到self.isAnimatingfalse,尽管它只动画了一次。

2 个答案:

答案 0 :(得分:8)

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

demo

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 }
    }
}

答案 1 :(得分:2)

我认为这就是您要寻找的东西

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: {
            self.peopleViewModel.load()
        }, label: {
            Image(systemName: "arrow.2.circlepath")
                .rotationEffect(Angle(degrees: self.isAnimating ? 360.0 : 0.0))
                .animation(self.foreverAnimation)
                .onAppear {
                    self.isAnimating = true
            }
        })
    }
}