animation - SwiftUI 同步多个带有延迟的 SwiftUI 动画
问题描述
我正在尝试构建一个包含多个项目的视图,这些项目应该彼此同步动画;例如,如果一项为 25%,则其他三项应为 50%、75% 和 100%。
刚开始使用的幼稚选项.delay(delay)
似乎可以完美地工作,但是一旦我切换应用程序,不同的动画都会被重置为完全偏移(不再有任何偏移)。我尝试了许多 hacky 解决方法,包括:
- 当视图背景/恢复时切换整个动画容器;这不起作用。(我认为是因为容器与动画状态一起保留,即使它不可见。)
- 使用
DispatchQueue.main.asyncAfter()
; 这与动画没有任何不同(因为我认为它是内部动画状态本身丢失了。)
请注意,我根本没有投资于这个特定的解决方案。任何有关解决此问题的更好方法的建议都非常受欢迎。
struct MyRepeatingItemView: View {
var delay: Double
@State
var isTranslated = false
var body: some View {
Color.red
.opacity(0.2)
.frame(width: 256, height: 256)
.scaleEffect(isTranslated ? 1 : 0.01)
.onAppear {
withAnimation(Animation.linear(duration: 4).repeatForever(autoreverses: false).delay(delay)) {
isTranslated.toggle()
}
}
}
}
struct MyRepeatingContainerView: View {
var body: some View {
ZStack {
Color.blue
.frame(width: 256, height: 2)
Color.blue
.frame(width: 2, height: 256)
MyRepeatingItemView(delay: 0.0)
MyRepeatingItemView(delay: 1.0)
MyRepeatingItemView(delay: 2.0)
MyRepeatingItemView(delay: 3.0)
}
}
}
解决方案
不同步视图的修复方法是将它们全部放在一个视图中,并且该视图会同时同步所有内容。我花了一些时间来制定模式,但这里是:
struct MyRepeatingItemView: View {
@State var isTranslated = false
var body: some View {
ZStack {
Rectangle()
.fill(Color.red)
.frame(width: 256, height: 256)
.opacity(isTranslated ? 0 : 0.25)
.scaleEffect(isTranslated ? 1 : 0.75)
Rectangle()
.fill(Color.red)
.frame(width: 256, height: 256)
.opacity(0.25)
.scaleEffect(isTranslated ? 0.75 : 0.5)
Rectangle()
.fill(Color.red)
.frame(width: 256, height: 256)
.opacity(0.25)
.scaleEffect(isTranslated ? 0.5 : 0.25)
Rectangle()
.fill(Color.red)
.frame(width: 256, height: 256)
.opacity(0.25)
.scaleEffect(isTranslated ? 0.25 : 0)
}
.onAppear {
withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
isTranslated.toggle()
}
}
}
}
struct MyRepeatingContainerView: View {
var body: some View {
ZStack {
Color.blue
.frame(width: 256, height: 2)
Color.blue
.frame(width: 2, height: 256)
MyRepeatingItemView()
}
}
}
推荐阅读
- python - 将所有以相同名称开头的文件复制到python中的不同目录
- sql - 函数返回字符串并更改编码
- angular - 如何从子组件切换材质选项卡
- entity-framework - EF Core 迁移采用旧迁移更改以及新列
- python - selenium wedriver程序无法继续
- django - 在 QuerySet 中的所有对象中递增特定参数
- awk - 如果 awk 从处理表达式返回 null,如何返回 0?
- swift - 授权标头在使用 Swift 的请求中消失
- sql - Azure 数据工厂 V2 复制数据问题 - 错误代码:2200 已添加具有相同密钥的项目
- php - PHP 正在我的表中创建两行,一行可以,但额外空