CZ54
CZ54

Reputation: 5588

Create Parallax using SwiftUI

I'm trying to create a parallax effect using SwiftUI.

This is my implementation :

import SwiftUI

struct ContentView: View {

    @State var parralaxOffset: CGFloat = 0

    var body: some View {
        ZStack {
            ScrollView {
                Text("Background")
            }.offset(x: 0, y: parralaxOffset)

           ScrollView {
                GeometryReader { reader in
                    Text("Foreground contentOffset: \(reader.frame(in: .global).minY)")
                }
            }
        }
    }
}

My question is: how to set the reader.frame(in: .global).minY) into the parralaxOffset variable ?

Upvotes: 1

Views: 1966

Answers (1)

Sam Pettersson
Sam Pettersson

Reputation: 3227

There is currently a bug (or intended effect) where you can't define or set variables inside a GeometryReader. As a workaround you can define a function which handles the operation instead, like so:

import SwiftUI

struct ContentView: View {

    @State var parralaxOffset: CGFloat = 0

    func handleParralax(_ reader: GeometryProxy) -> some View {
        self.parralaxOffset = reader.frame(in: .global).minY
        return Text("Foreground contentOffset: \(reader.frame(in: .global).minY)")
    }

    var body: some View {
        ZStack {
            ScrollView {
                Text("Background")
            }.offset(x: 0, y: parralaxOffset)

           ScrollView {
                GeometryReader { reader in
                    self.handleParralax(reader)
                }
            }
        }
    }
}

Upvotes: 2

Related Questions