SwiftUI跨两个视图绑定变量控制动画速度变化的问题求解
解决方案
问题根源
- 未将
ContentView中的animationDuration绑定值传入SplashView,导致SplashView一直使用默认的0.1常量作为动画时长,滑块修改无法生效 SplashView未监听外部传入的颜色变化,切换颜色时内部的colorStore不会更新,无法触发新的动画逻辑
修改步骤
1. 修改ContentView的SplashView初始化代码
在ContentView的body中,找到SplashView实例化的代码,补充传入animationDuration绑定参数:
SplashView(animationType: .leftToRight, color: self.colors[self.index], animationDuration: $animationDuration)
2. 修改SplashView代码
2.1 新增color属性,接收外部传入的颜色值
在SplashView的属性定义部分新增如下代码:
var color: Color
2.2 监听颜色变化更新colorStore
在SplashView的body最后(onReceive修饰符之后)新增onChange修饰符,监听外部颜色变化:
.onChange(of: color) { newColor in colorStore.color = newColor }
2.3 可选优化:清理冗余图层(避免内存占用持续升高)
如果需要兼容iOS 17及以上版本,可以将onReceive中的动画代码修改为如下形式,动画结束后清理图层:
withAnimation(.easeInOut(duration: self.animationDuration)) { self.layers[self.layers.count - 1].1 = 1.0 } completion: { self.prevColor = color self.layers.removeAll() }
如果需要兼容更低iOS版本,可以替换为延时处理逻辑:
withAnimation(.easeInOut(duration: self.animationDuration)) { self.layers[self.layers.count - 1].1 = 1.0 } DispatchQueue.main.asyncAfter(deadline: .now() + animationDuration) { self.prevColor = color self.layers.removeAll() }
内容的提问来源于stack exchange,提问作者Konrad
相关产品推荐
相关产品推荐

