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

SwiftUI中如何让Circle同时实现滑动与缩放过渡效果?

SwiftUI 同时实现滑动+缩放过渡的问题解决

你的代码核心问题是连续添加多个.transition修饰符时,只有最后一个会生效——SwiftUI的同类型修饰符是按顺序覆盖的,后面的.transition(.scale)会直接替换掉前面的.transition(.slide),所以无法同时触发两个过渡效果。

要实现滑动与缩放的组合动画,需要用AnyTransition的.combined(with:)方法将两个过渡效果合并,而非单独添加多个.transition修饰符。

修改后的完整代码如下:

import SwiftUI

@main
struct BouncingApp: App {
    var body: some Scene {
        WindowGroup {
            BounceAble()
        }
    }
}

struct BounceAble: View {
    @State var bounce: Bool = false
    
    var body: some View {
        VStack(alignment: .center) {
            Button("Bounce") {
                withAnimation(.easeOut) {
                    bounce.toggle()
                }
            }
        }
        .overlay {
            if bounce {
                Circle()
                    .frame(width: 200, height: 200)
                    // 组合滑动与缩放过渡效果
                    .transition(.slide.combined(with: .scale))
                    .onTapGesture {
                        withAnimation(.easeIn) {
                            bounce.toggle()
                        }
                    }
            }
        }
    }
}

如果需要定制过渡细节,还可以给过渡添加参数,比如调整缩放幅度:.scale(scale: 0.2),或者修改滑动方向:.move(edge: .bottom)(替代默认的.slide),组合后依然能同时生效。

内容的提问来源于stack exchange,提问作者Steven-Carrot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:24:23