swift - 在 SwiftUI 图像上重复动画

标签 swift xcode swiftui

给定以下结构:

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

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

最佳答案

这是在出现和开始/停止时持续前进的可能解决方案。使用 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 }
    }
}

关于swift - 在 SwiftUI 图像上重复动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315628/

相关文章:

ios - 一次加载 10 个单元格行 - swift

swift - 如何实现堆栈 View ?

ios - 更改 QLPreviewController 中的导航栏颜色

swift - 如何为父 ScrollView 之外的 View 设置动画

ios - IAP SKErrorDomain 代码=0 Swift

ios - 状态栏整个 View 下移 - iOS 11

iphone - 在 Xcode 中移动指定区域内的对象

iPhone 设置后栏按钮项目的色调颜色

SwiftUI - TabView 内的 OnExitCommand

ios - 如何处理 UIViewControllerRepresentable 包装器内的 NavigationLink?