< How to make a scroll view move to a location using ScrollViewReader | How to position views in a grid using LazyVGrid and LazyHGrid > |
Updated for Xcode 12.5
If we combine GeometryReader
with any view that can change position – such as something that has a drag gestures or is inside a List
– we can create 3D effects that look great on the screen. GeometryReader
allows us to read the coordinates for a view, and feed those values directly into a rotation3DEffect()
modifier.
For example, we could create a Cover Flow-style scrolling effect by stacking up many text views horizontally in a scroll view, then applying rotation3DEffect()
so that as they move in the scroll view they gently spin, like this:
struct ContentView: View {
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
ForEach(1..<10) { num in
VStack {
GeometryReader { geo in
Text("Number \(num)")
.font(.largeTitle)
.padding()
.background(Color.red)
.rotation3DEffect(.degrees(-Double(geo.frame(in: .global).minX) / 8), axis: (x: 0, y: 1, z: 0))
}
}
.frame(width: 180)
}
}
.padding()
}
}
}
You don’t always need to use GeometryReader
to get interesting effects like – you could something similar with a DragGesture()
, for example. So, this code creates a card-like rectangle that can be dragged around in both X and Y axes, and uses two rotation3DEffect()
modifiers to apply values from that drag:
struct ContentView: View {
@State var dragAmount = CGSize.zero
var body: some View {
VStack {
Rectangle()
.fill(LinearGradient(gradient: Gradient(colors: [.yellow, .red]), startPoint: .topLeading, endPoint: .bottomTrailing))
.frame(width: 300, height: 200)
.clipShape(RoundedRectangle(cornerRadius: 20))
.rotation3DEffect(.degrees(-Double(dragAmount.width) / 20), axis: (x: 0, y: 1, z: 0))
.rotation3DEffect(.degrees(Double(dragAmount.height / 20)), axis: (x: 1, y: 0, z: 0))
.offset(dragAmount)
.gesture(
DragGesture()
.onChanged { dragAmount = $0.translation }
.onEnded { _ in
withAnimation(.spring()) {
dragAmount = .zero
}
}
)
}
}
}
As you drag the card around you’ll see it rotates to give a perspective effect.
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.