【问题标题】:SwiftUI animation not working using animation(_:value:)SwiftUI 动画无法使用动画(_:value :)
【发布时间】:2022-01-23 12:25:52
【问题描述】:

在 SwiftUI 中,我已经使用 animation(_:) 修饰符成功地在视图首次绘制到屏幕时制作了一个 Button 动画,该修饰符在 macOS 12 中已被弃用。

我尝试用新的 animation(_:value:) 修饰符替换它,但这次什么也没发生: 所以这是行不通的:

struct ContentView: View {
    @State var isOn = false
    var body: some View {
        Button("Press me") {
            isOn.toggle()
        }
        .animation(.easeIn, value: isOn)
        .frame(width: 300, height: 400)
    }
}

但这是有效的。为什么?

struct ContentView: View {
    var body: some View {
        Button("Press me") {
        }
        .animation(.easeIn)
        .frame(width: 300, height: 400)
    }
}

第二个示例在视图显示时为按钮设置动画,而第一个示例不执行任何操作

【问题讨论】:

  • 需要最小的可重现示例。
  • 当视图出现时你是否改变showChat?显式动画监视 init 中包含的值的变化。
  • @Yrb 当按钮切换showChat时,整个视图被关闭
  • 请发帖Minimal, Reproducible Example。不鼓励使用外部链接,我们不需要浏览您的整个应用程序。只需制作一个显示您的问题的最小示例即可。

标签: swiftui swiftui-animation


【解决方案1】:

animation(_:)animation(_:value:) 之间的区别很简单。前者是隐式的,后者是显式的。 animation(_:) 的隐含性质意味着任何时候发生任何变化,它都会做出反应。它的另一个问题是试图猜测你想要动画什么。因此,这可能是不稳定和出乎意料的。还有一些其他问题,所以 Apple 干脆弃用了它。

animation(_:value:) 是一个显式动画。它只会在你给它的值改变时触发。这意味着您不能只将其粘贴在视图上并期望视图在它进入时会产生动画效果。您需要更改 .onAppear() 中的值或使用在视图出现触发动画时自然变化的值。您还需要有一些修饰符专门对更改的值做出反应。

struct ContentView: View {
    @State var isOn = false
    //The better route is to have a separate variable to control the animations
    // This prevents unpleasant side-effects.
    @State private var animate = false
    
    var body: some View {
        VStack {
            Text("I don't change.")
                .padding()
            Button("Press me, I do change") {
                isOn.toggle()
                animate = false
                // Because .opacity is animated, we need to switch it
                // back so the button shows.
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    animate = true
                }
            }
            // In this case I chose to animate .opacity
            .opacity(animate ? 1 : 0)
            .animation(.easeIn, value: animate)
            .frame(width: 300, height: 400)
            // If you want the button to animate when the view appears, you need to change the value
            .onAppear { animate = true }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多