通过回调跟踪 SwiftUI 动画进度和完成情况
SwiftUI Animation Observer
通过回调跟踪 SwiftUI 动画进度和完成情况!对于动画值(偏移量、不透明度等),请在动画进行时获取其当前值,然后在动画完成时收到通知。
安装
此组件作为 Swift 包分发。只需将此存储库的 URL 添加到 XCode 中:
https://github.com/globulus/swiftui-animation-observer
如何使用
将修饰符添加到视图中。传递其值由动画更改的属性和两个可选回调:animationObserver
onProgress
在每个动画帧上调用,并报告动画属性的当前值。onComplete
在动画完成时调用。
struct AnimationObserverTest: View {
@State private var offset = 0.0
@State private var offsetSpan: ClosedRange<Double> = 0...1
@State private var progressPercentage = 0.0
@State private var isDone = false
var body: some View {
GeometryReader { geo in
VStack {
Text("Loading: \(progressPercentage)%")
Rectangle()
.foregroundColor(.blue)
.frame(height: 50)
.offset(x: offset)
.animationObserver(for: offset) { progress in // HERE
progressPercentage = 100 * abs(progress - offsetSpan.lowerBound) / (offsetSpan.upperBound - offsetSpan.lowerBound)
} onComplete: {
isDone = true
}
if isDone {
Text("Done!")
} else if progressPercentage >= 50 {
Text("Woooooah, we're half way there...")
}
Button("Reload") {
isDone = false
offset = -geo.size.width
offsetSpan = offset...0
withAnimation(.easeIn(duration: 5)) {
offset = 0
}
}
}
}
}
}
Recipe
Check out this recipe for in-depth description of the component and its code. Check out SwiftUIRecipes.com for more SwiftUI recipes!
Changelog
- 1.0.0 – Initial release.