SwiftUI如何监听logo动画完成事件触发回调跳转其他视图
SwiftUI 动画完成后执行回调的实现方案
方案1:iOS 17+ 原生API(推荐)
iOS 17 开始withAnimation新增了完成回调参数,可以直接在动画结束后执行指定逻辑,修改你的animateSplash方法即可:
func animateSplash() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){ withAnimation(Animation.easeOut(duration: 0.8)) { animate.toggle() } completion: { // 动画完全结束后执行你的逻辑,比如跳转 isLoggedin = true // 调用自定义跳转函数 yourCustomJumpFunction() } } }
跳转视图可以配合NavigationStack或者fullScreenCover,用你现有的isLoggedin状态控制即可,示例:
在body的顶层ZStack中添加修饰符:
.fullScreenCover(isPresented: $isLoggedin) { // 替换为你要跳转的目标视图 TargetView() }
方案2:兼容iOS 13+ 低版本系统
如果需要支持iOS 17以下的系统,可以选择以下两种实现:
- 方式1:按动画总时长延迟调度
你当前的动画逻辑是先等待0.4秒再执行0.8秒的动画,总时长为1.2秒,直接加对应时长的延迟调度即可:
func animateSplash() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){ withAnimation(Animation.easeOut(duration: 0.8)) { animate.toggle() } // 等待动画执行完成后触发逻辑 DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { isLoggedin = true yourCustomJumpFunction() } } }
- 方式2:通过Transaction监听动画完成
这种方式不需要硬编码时长,兼容性更好:
func animateSplash() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.4){ var transaction = Transaction(animation: .easeOut(duration: 0.8)) transaction.completion = { // 动画完成回调 isLoggedin = true yourCustomJumpFunction() } withTransaction(transaction) { animate.toggle() } } }
内容的提问来源于stack exchange,提问作者Seb
相关产品推荐
相关产品推荐

