gpt4 book ai didi

ios - 带有 switch 语句的 SwiftUI 动画

转载 作者:行者123 更新时间:2023-12-02 02:22:02 25 4
gpt4 key购买 nike

我了解简单动画在 SwiftUI 中的工作原理。但是,我有一个稍微复杂的 watchOS 应用程序。 View 状态由 switch 语句处理:

struct ContentView: View {
@EnvironmentObject private var state: AppState

@State private var selection = 1

var body: some View {
Group {
switch state.view {
case .start:
TabView(selection: $selection) {
ActivityView()
.tag(0)
StartView()
.tag(1)
SettingsView()
.tag(2)
}
case .workout:
TabView(selection: $selection) {
TakeoffControlView()
.tag(0)
TakeoffView()
.tag(1)
}
}

// ...
}
}
}

在另一个 View 中我编辑 View 状态:

struct StartView: View {
@EnvironmentObject private var state: AppState

var body: some View {
Button(action: {
state.view = .workout
}, label: {
Text("Start")
})
}
}

如何添加动画以在不同情况之间进行转换?我尝试向 GroupTabView 和单个 View 添加动画,但没有成功。显然,我将状态更改包装在 withAnimation 中。但是,我无法让它发挥作用。任何想法如何使这项工作?

最佳答案

.transition() 只是定义过渡是什么,要获得预期的过渡动画,您必须在 withAnimation 中对 SourceOfTruth 进行更改() { ... } block 。

struct ContentView: View {
@EnvironmentObject private var state: AppState

@State private var selection = 1

var body: some View {
Group {
switch state.view {
case .start:
TabView(selection: $selection) {
ActivityView()
.tag(0)
StartView()
.tag(1)
SettingsView()
.tag(2)
}
.transition(.slide)//<- here

case .workout:
TabView(selection: $selection) {
TakeoffControlView()
.tag(0)
TakeoffView()
.tag(1)
}
.transition(.slide)//<- here
}

// ...
}
}
}

struct StartView: View {
@EnvironmentObject private var state: AppState

var body: some View {
Button(action: {
withAnimation(.easeIn) { //<- here
state.view = .workout
}
}, label: {
Text("Start")
})
}
}

关于ios - 带有 switch 语句的 SwiftUI 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66270438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com