你能在 SwiftUI 中使用transformEffect和scrollTransition吗?

问题描述 投票:0回答:1

我想用 scrollTransition 创建一些翻译效果。

这是一个使用scaleEffect的例子。我尝试过使用 transformEffect 进行翻译,但该修饰符似乎不适用于scrollTransition。还有其他方法可以创建翻译效果吗?

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
                                    .scaleEffect(phase.isIdentity ? 1 : 0.6)
                            }
                    }
                    .containerRelativeFrame(.horizontal, count: 1, spacing: 0)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned)
    }
}
swift swiftui
1个回答
0
投票

使用

.offset(x:y:)
。示例:

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(y: phase.isIdentity ? 0 : 100)
                                    .scaleEffect(phase.isIdentity ? 1 : 0.6)
                                    .opacity(phase.isIdentity ? 1.0 : 0.0)
                            }
                    }
                    .containerRelativeFrame(.horizontal, count: 1, spacing: 0)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.