gpt4 book ai didi

swift - Swiftui withAnimation(.linear) 中的持续时间参数

转载 作者:行者123 更新时间:2023-12-05 03:37:00 29 4
gpt4 key购买 nike

我在研究 Swift UI 的线性动画技术时发现,与我的预期相反,增加持续时间似乎并没有使动画发生得更慢。这是故意的吗?如果是这样,我该如何制作较慢的动画?

示例代码:

struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
withAnimation(.linear(duration: 50)) {
CollapsibleView()
}
}
}
Button(action: { show = !show }) {
Text("Press Me")
}
}
}


struct CollapsibleView: View {
var body: some View {
VStack {
Text("Text 1")
Text("Text 2")
Text("Text 3")
}
}
}

@main
struct app: App {
var body: some Scene {
WindowGroup {
ButtonView()
}
}
}

尝试更改持续时间参数,看看您是否能注意到较慢的动画。我达到了 5000(我假设这是以秒为单位?)并且它仍然以看似相同的速度进行动画处理。

最佳答案

您已将 withAnimation 放置在 View 层次结构中。您真正想要它的地方是在 Button 的操作中:

struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
Button(action: {
withAnimation(.linear(duration: 10)) {
show.toggle()
}

}) {
Text("Press Me")
}
}
}

或者,您可以在 ZStack 上使用 .animation:

struct ButtonView: View {
@State var show: Bool = false
var body: some View {
ZStack{
if show {
CollapsibleView()
}
}
.animation(.linear(duration: 10), value: show)
Button(action: {
show.toggle()
}) {
Text("Press Me")
}
}
}

关于swift - Swiftui withAnimation(.linear) 中的持续时间参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69487825/

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