【问题标题】:Duration parameter on Swift UI withAnimation(.linear)Swiftui 中的 Duration 参数 withAnimation(.linear)
【发布时间】:2021-10-07 21:02:24
【问题描述】:

我在搞乱 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(我假设这是以秒为单位?)它仍然以看似相同的速度制作动画。

【问题讨论】:

    标签: swift animation swiftui


    【解决方案1】:

    您已将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")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多