【问题标题】:SwiftUI ButtonStyle animation causes UI not to update in App Switcher snapshot when system appearance changes当系统外观发生变化时,SwiftUI ButtonStyle 动画导致 UI 在 App Switcher 快照中不更新
【发布时间】:2026-01-26 19:20:02
【问题描述】:

在我的应用程序中,我有一个按钮,我想在触摸它时对其进行动画缩小。为此,我创建了一个自定义ButtonStyle,并带有显式animation。这按预期工作,但在暗/亮模式系统外观之间切换时引入了问题。如果在应用程序打开时更改它,Color 会按预期更新,但如果应用程序未打开,则应用程序切换器中的快照显示新系统外观的错误颜色。以下代码在浅色模式下应该是白色背景上的黑框,在深色模式下应该是黑色背景上的白色。背景总是正确更新,但盒子在快照中仍然是旧颜色,因此你看不到它 - 黑底黑或白底白字 - 至少在 iOS 14.2 中是这样。问题是animation - 如果我删除快照按预期显示。为什么会这样,我该如何解决?

struct ContentView: View {
    var body: some View {
        Button(action: {}) {
            Color.primary
                .frame(height: 100)
        }
        .buttonStyle(MyButtonStyle())
        .padding()
    }
}

struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.8 : 1)
            .animation(.easeOut(duration: 0.5)) //FIXME: Removing this fixes it
    }
}

这里我在亮模式下运行应用程序,然后我关闭它,启用暗模式,然后打开 App Switcher 发现盒子在黑色背景上是黑色的。该框应该是白色的,就像我点击应用程序将其返回到前台时一样。

【问题讨论】:

    标签: ios swift swiftui ios-darkmode swiftui-14.2-defect


    【解决方案1】:

    适用于 iOS 14.1,所以我认为这是 14.2 的另一个缺陷。

    尝试将动画链接到值(未经测试,只是想法):

    struct MyButtonStyle: ButtonStyle {
        func makeBody(configuration: Self.Configuration) -> some View {
            configuration.label
                .scaleEffect(configuration.isPressed ? 0.8 : 1)
                .animation(.easeOut(duration: 0.5), value: configuration.isPressed)
        }
    }
    

    【讨论】: