SwiftUI中LoadingView在iOS 14上表现异常的修复咨询
iOS 14 上 SwiftUI LoadingView 动画异常的修复方案
问题描述
我在某个视图中使用 LoadingView 等待网络数据加载完成,该视图在 iOS 13 上显示正常,但在 iOS 14 上表现异常。视图代码如下:
import SwiftUI struct LoadingView: View { @State private var shouldAnimate = false var body: some View { HStack { Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever()) Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.3)) Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.6)) } .onAppear { self.shouldAnimate = true } } }
问题原因
iOS 14 对 SwiftUI 的动画系统做了针对性调整,强化了动画触发的显式性。在 iOS 13 中,未指定value参数的隐式动画可以自动响应@State变量的变化,但 iOS 14 要求必须明确绑定动画依赖的状态值,否则重复动画可能无法正确启动或维持循环状态。
修复方案
给每个animation修饰符添加value: shouldAnimate参数,明确告诉 SwiftUI:当shouldAnimate状态变化时触发对应的动画。修改后的代码如下:
import SwiftUI struct LoadingView: View { @State private var shouldAnimate = false var body: some View { HStack { Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever(), value: shouldAnimate) Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.3), value: shouldAnimate) Circle() .fill(Color.primary) .frame(width: 30, height: 30) .scaleEffect(shouldAnimate ? 1.0 : 0.5) .animation(Animation.easeInOut(duration: 0.5).repeatForever().delay(0.6), value: shouldAnimate) } .onAppear { self.shouldAnimate = true } } }
额外优化建议
如果想让动画启动更平滑,也可以在onAppear中结合withAnimation显式触发状态变化:
.onAppear { withAnimation { self.shouldAnimate = true } }
两种方式结合后,能确保 LoadingView 在 iOS 14 及更高版本中的表现和 iOS 13 完全一致。
内容的提问来源于stack exchange,提问作者Sami Alfhaily
相关产品推荐
相关产品推荐

