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("成功回调了")
    }
相关推荐
茶底世界之下2 小时前
预乘 Alpha 图层合成为什么会越叠越暗?
架构·swift
茶底世界之下7 小时前
花瓣要更柔和,还是更有反差?用 Awaking 做一次对比度取舍
ios
Anhty1 天前
2026最新免费手机音频处理工具 !!
android·功能测试·ios·智能手机·音视频
2501_915909061 天前
iOS应用从开发到上架App Store的完整发布流程与步骤指南
android·ios·小程序·https·uni-app·webview
初雪云1 天前
UniApp 云打包拿到 IPA 后,真正的发布工作才刚开始
ios·自动化·编辑器·产品经理·iphone
Lancker1 天前
没有 Mac 也能上架 iOS:GitHub Actions 全自动构建 + 签名 + TestFlight 送审实录
macos·ios·github
茶底世界之下1 天前
晚霞要多暖?用 Awaking 只改色温做一次取舍
ios
酒神dnspup1 天前
多地区网站可用性监控怎么做?DNSPup 从基线到告警的完整实战
运维·ios·云计算·iphone·dns·网络监控
福兮说2 天前
浏览器里把 iPhone 的 HEIC 转成 JPG:Chrome 解不开、转完大了七成、拍摄时间全丢,六个坑实测
前端·javascript·图像处理·chrome·ios·iphone·heic
茶底世界之下2 天前
时间线效果层,为什么不能只复用一个处理器?
ios·swift