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("成功回调了")
    }
相关推荐
@大迁世界1 天前
iOS 26.2 引入三种全新 iPhone 自定义方式
ios·iphone
Sheffi661 天前
iOS 触摸事件完整传递链路:Hit-Test 全流程深度解析
macos·ios·cocoa
Swift社区1 天前
用 Task Local Values 构建 Swift 里的依赖容器:一种更轻量的依赖注入思路
开发语言·ios·swift
2501_915909061 天前
苹果应用加密方案的一种方法,在没有源码的前提下,如何处理 IPA 的安全问题
android·安全·ios·小程序·uni-app·iphone·webview
TouchWorld1 天前
iOS逆向-哔哩哔哩增加3倍速播放(4)- 竖屏视频·全屏播放场景
ios·swift
2501_915909061 天前
iOS 项目中常被忽略的 Bundle ID 管理问题
android·ios·小程序·https·uni-app·iphone·webview
2501_915921431 天前
iOS App 测试的工程化实践,多工具协同的一些尝试
android·ios·小程序·https·uni-app·iphone·webview
denggun123451 天前
ios卡顿监测和优化(二)
ios