SwiftUI Catch the Ball Game: Animation inside Geometry Reader

DevTechie Inc
Jun 24, 2022

In this article, we will see an example of animation inside GeometryReader. We will build a very simple game out of this.

Game goes like this, as soon as the screen is launched, a ball on the screen will move. Goal is to tap on the ball while its resting between moves. This simple game will show you position animation in GeometryReader.

struct GeometryReaderAnimation: View {
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()    @State private var animate = false    var body: some View {
        GeometryReader { geo in 
            Circle()
                .fill(RadialGradient(colors: [.white, .blue], center: .center, startRadius: 1, endRadius: 20))
                .frame(width: 30)
                .position(CGPoint(x: Double.random(in: 10..<geo.size.width), y: Double.random(in: 10..<geo.size.height)))
                .animation(.spring(), value: animate)
                .onTapGesture {
                    timer.upstream.connect().cancel()
                }
        }
        .onReceive(timer, perform: { _ in
            animate.toggle()
        }) 
    }
}


With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com