Duration参数在Swift UI withAnimation(.linear)上



我正在摆弄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()
}
}
}

尝试更改duration参数,看看是否可以注意到较慢的动画。我将其设置为5000(我假设这是以秒为单位?),并且它仍然以看似相同的速度动画。

您已经将withAnimation放置在视图层次结构中。你真正需要它的地方是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")
}
}
}

最新更新