在ios17中withAnimation有completion方法可以监听动画完成,但是低于ios17没有,需要自定义一个监听器,原理就是通过AnimatableModifier可以监听到值的didSet修改,我们就可以调用回调函数。
代码
swift
// 动画完成监听
struct AnimatableCompletionModifier<Value>: AnimatableModifier where Value: VectorArithmetic {
var animatableData: Value {
didSet {
notifyCompletionIfFinished()
}
}
private var targetValue: Value
private var completion: () -> Void
init(observedValue: Value, completion: @escaping () -> Void) {
self.completion = completion
animatableData = observedValue
targetValue = observedValue
}
private func notifyCompletionIfFinished() {
guard animatableData == targetValue else { return }
DispatchQueue.main.async {
self.completion()
}
}
func body(content: Content) -> some View {
return content
}
}
extension View {
func onAnimationCompleted<Value: VectorArithmetic>(for value: Value, completion: @escaping () -> Void) -> ModifiedContent<Self, AnimatableCompletionModifier<Value>> {
modifier(AnimatableCompletionModifier(observedValue: value, completion: completion))
}
}
使用
swift
Text("回调")
.opacity(introTextOpacity)
.onAnimationCompleted(for: introTextOpacity) {
print("成功回调了")
}