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("成功回调了")
    }
相关推荐
sakiko_8 小时前
Swift学习笔记39-实战注意事项
前端·笔记·学习·swift
东坡肘子12 小时前
Apple Intelligence 已通过审核,即将在中国提供服务 -- 肘子的 Swift 周报 #148
人工智能·swiftui·swift
CHB1 天前
uni-app x 蒸汽模式 性能测试基准报告 Benchmark【Android版】
android·ios·uni-app
Magic-ZYJ1 天前
不登录、不联网也能用:我是如何设计一款“本地优先”iOS App 的
ios·app·iphone·研发·独立开发者·心情日记
_阿南_1 天前
flutter 展示的字体突然奔放了
android·flutter·ios
90后的晨仔1 天前
你的 iOS 最低部署版本即将不再被 App Store 接受
ios
2601_965798471 天前
Launch Your Wellness App Fast: The Truth About Meditation Source Code
前端·macos·ios·objective-c·cocoa
初级代码游戏2 天前
iOS开发 Swift 速记7:结构体和类
开发语言·ios·swift
Anhty2 天前
手机端叮咚变声器2026实测:功能表现、优缺点完整解析
功能测试·ios·智能手机·安卓
SameX2 天前
后台定位耗电的问题,我花两年把它压到了3%-5%
ios