SwiftUI使用offset()隐藏组件时动画混乱问题如何解决
问题根因
你遇到的动画冲突是SwiftUI动画上下文未隔离导致的:按钮上的无限重复呼吸动画未绑定对应触发值,父视图隐藏面板触发的动画会被按钮的动画修饰符捕获,导致过渡异常。
可行解决方案
以下方案可单独使用,也可搭配使用进一步保证动画隔离:
- 方案1:给按钮的动画绑定触发值(推荐,iOS 15+适用)
将GenericButtonViews中按钮的动画修饰符增加value参数,限定动画仅响应录音状态变化,不会被父视图的面板显隐动画干扰:
// 替换原有的.animation行 .animation(model.isAudioRecording && buttonType == .styled ? Animation.linear(duration: 1).repeatForever(autoreverses: true) : .none, value: model.isAudioRecording)
- 方案2:给父视图的显隐动画绑定触发值
将MainView中面板的动画修饰符增加value参数,限定动画仅响应面板显隐状态变化:
// 替换原有的.animation行 .animation(.spring(blendDuration: 0.25), value: model.showingBtnPanel)
- 方案3:兼容低iOS版本的实现方式
如果需要支持iOS 15以下版本,可以移除按钮上的全局animation修饰符,将呼吸动画的触发放在按钮点击的withAnimation闭包内,主动控制动画的启停:
// 修改ButtonPanel.swift中按钮的action逻辑 action: { let newRecordingState = !model.isAudioRecording if newRecordingState { withAnimation(.linear(duration: 1).repeatForever(autoreverses: true)) { model.isAudioRecording = newRecordingState } } else { withAnimation(.default) { model.isAudioRecording = newRecordingState } } model.toggleEngine() }
内容的提问来源于stack exchange,提问作者Duc Dang
相关产品推荐
相关产品推荐

