Swift withAnimation 动画完成监听

在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("成功回调了")
    }
相关推荐
karshey16 小时前
【IOS webview】h5页面播放视频时,IOS系统显示设置的icon
前端·ios
游戏开发爱好者816 小时前
抓包工具有哪些?代理抓包、数据流抓包、拦截转发工具
android·ios·小程序·https·uni-app·iphone·webview
bybitq18 小时前
Go函数闭包实战-复用函数
ios·golang·xcode
renke336420 小时前
Flutter 2025 跨平台工程体系:从 iOS/Android 到 Web/Desktop,构建真正“一次编写,全端运行”的产品
android·flutter·ios
Zender Han21 小时前
Flutter 中 AbsorbPointer 与 IgnorePointer 的区别与使用场景详解
android·flutter·ios
Digitally1 天前
3种简单方法备份 iPhone 短信
ios·iphone
2501_915921431 天前
Flutter App 到底该怎么测试?如何在 iOS 上进行测试
android·flutter·ios·小程序·uni-app·cocoa·iphone
二流小码农1 天前
鸿蒙开发:一个底部的曲线导航
android·ios·harmonyos