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

SwiftUI中能否结合scrollTransition使用transformEffect实现平移效果?

实现scrollTransition平移效果的替代方案

你可以使用offset修饰符来替代transformEffect实现平移效果,它能很好地和scrollTransition配合使用。另外还可以利用ScrollTransitionPhase的progress属性实现平滑的过渡动画效果,以下是两种具体实现方式:

方式一:固定偏移量平移

直接通过offset设置固定的平移距离,在视图处于非激活(非isIdentity)状态时应用偏移:

struct ContentView: View {
    var colors: [Color] = [.blue, .green, .yellow, .orange, .red]
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack(spacing: 0) {
                ForEach(colors, id: \.self) { color in
                    ZStack {
                        Rectangle()
                            .foregroundStyle(color)
                        
                        Rectangle()
                            .foregroundStyle(.black)
                            .frame(width: 100, height: 100)
                            .scrollTransition { content, phase in
                                content
                                    .offset(x: phase.isIdentity ? 0 : 100) // 非激活时向右平移100
                                    .scaleEffect(phase.isIdentity ? 1 : 0.6) // 保留原有缩放效果
                            }
                    }
                    .containerRelativeFrame(.horizontal, count: 1, spacing: 0)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned)
    }
}

方式二:基于progress的平滑平移

利用phase.progress的值(范围0到1)实现随滚动进度变化的平滑平移,过渡更自然:

struct ContentView: View {
    var colors: [Color] = [.blue, .green, .yellow, .orange, .red]
    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack(spacing: 0) {
                ForEach(colors, id: \.self) { color in
                    ZStack {
                        Rectangle()
                            .foregroundStyle(color)
                        
                        Rectangle()
                            .foregroundStyle(.black)
                            .frame(width: 100, height: 100)
                            .scrollTransition(.animated) { content, phase in
                                content
                                    .offset(x: phase.progress * 100) // 随进度从0到100平移
                                    .scaleEffect(phase.isIdentity ? 1 : 0.6)
                            }
                    }
                    .containerRelativeFrame(.horizontal, count: 1, spacing: 0)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned)
    }
}

说明

  • offset(x:)控制水平平移,offset(y:)可控制垂直平移,根据需求调整数值即可。
  • phase.progress会根据视图的滚动状态动态变化:视图进入视口时从0递增到1,离开时从1递减到0,适合做连续的过渡动画。
  • 如果需要反向平移,只需将偏移数值设为负数即可(比如-100)。

内容的提问来源于stack exchange,提问作者Berry Blue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:18:14