You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何实现单按钮文本切换与偏移同步流畅动画

单个SwiftUI按钮实现文本切换与偏移同步的流畅动画

要实现单个按钮的文本切换与偏移量变化同步的流畅动画,无需使用两个独立按钮,只需在按钮内部通过matchedGeometryEffect绑定两种状态的文本,配合显隐控制即可达成效果。修改后的代码如下:

struct Button_Animation: View {
    @State var isEnabled = true
    @Namespace var namespace

    var body: some View {
        ZStack {
            Color.white
                .ignoresSafeArea()

            VStack {
                Toggle("", isOn: $isEnabled)
                    .labelsHidden()

                Button(action: {}) {
                    // 用ZStack承载两种状态的文本
                    ZStack {
                        Text("ENABLED")
                            // 绑定同一个几何效果标识,实现位置过渡
                            .matchedGeometryEffect(id: "buttonText", in: namespace)
                            .opacity(isEnabled ? 1 : 0)
                        Text("DISABLED")
                            .matchedGeometryEffect(id: "buttonText", in: namespace)
                            .opacity(isEnabled ? 0 : 1)
                    }
                }
                .offset(y: isEnabled ? 200 : -200)
                // 绑定动画到状态变量,确保所有变化同步触发
                .animation(.linear(duration: 1), value: isEnabled)
            }
        }
    }
}

关键实现逻辑

  • 几何效果绑定:两个文本使用相同的matchedGeometryEffect标识,SwiftUI会自动计算它们的位置差异,生成平滑的过渡动画。
  • 文本显隐控制:通过opacity属性控制对应状态文本的可见性,避免两个文本同时显示。
  • 同步动画触发:将动画绑定到isEnabled状态变量,按钮的偏移和文本的切换动画会同步执行,保证整体流畅性。

内容的提问来源于stack exchange,提问作者Nikita Ermolenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:55:14