WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Animate a view above all other views without affecting other views positions in SwiftUI

Forums > SwiftUI

In the following code, I'm trying to animate an Image above all other views. What I want is basically to animate the purple circle image above Bottom View but when I tap the purple image and the animation starts, the rest of the views move along with the animated image.

How can I animate a view above all other views without affecting other views' position?

View

    struct ContentView: View {
        @State private var isAnimating = false
        var body: some View {
            ZStack{
                VStack{
                    HStack{
                        Text("TOP View")
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)
                    .padding(.top)

                    HStack{
                        Image(systemName: "target")
                            .font(.largeTitle)
                            .foregroundColor(.red)
                        Spacer()
                    }
                    .padding(.vertical)

                    HStack{
                        Text("BOTTOM View")
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)

                    Image(systemName: "circle.fill")
                        .font(.system(size: 65))
                        .foregroundColor(.purple)
                        .throwAnimation(isAnimating: $isAnimating)
                        .onTapGesture {
                            isAnimating.toggle()
                        }
                        .zIndex(100)
                }
            }
        }
    }

Animation

    struct ThrowAnimationWrapper<Content: View>: UIViewRepresentable{
        @ViewBuilder let content: () -> Content
        @Binding var isAnimating: Bool
        func makeUIView(context: Context) -> UIView {
            UIHostingController(rootView: content()).view
        }
        func updateUIView(_ uiView: UIView, context: Context) {
            if isAnimating{

                uiView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0);// start at full scale

                let startPoint = CGPoint(x: 250, y: 500)
                let apexPoint = CGPoint(x: 100 + 50, y: 50 - 200)
                let endPoint = CGPoint(x: 50, y: 350)
                let durationTime = 0.8

                let path = UIBezierPath()
                path.move(to: startPoint)
                path.addQuadCurve(to: endPoint, controlPoint: apexPoint)

                CATransaction.begin() // to be able to capture the beggining of the animation
                CATransaction.setCompletionBlock({
                    print("Animation completed!")
                })
                let animation = CAKeyframeAnimation(keyPath: "position")
                animation.path = path.cgPath
                animation.duration = durationTime
                uiView.layer.add(animation, forKey: "bezier")
                uiView.center = endPoint

                UIView.animate(withDuration: durationTime, animations: {
                    uiView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5);
                })

                CATransaction.commit() // to be able to capture the end of the animation
            }
        }
    }

    extension View {
        func throwAnimation( isAnimating: Binding<Bool>) -> some View {
            modifier(ThrowAnimationViewModifier(isAnimating: isAnimating))
        }
    }
    struct ThrowAnimationViewModifier: ViewModifier {
        @Binding var isAnimating: Bool
        func body(content: Content) -> some View {
            ThrowAnimationWrapper(content: {
                content
            }, isAnimating: $isAnimating)
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Image

enter image description here

2      

Hi, You have to set the background of the uiView to clear so you dont see it when the ball moves.

func updateUIView(_ uiView: UIView, context: Context) {
        uiView.backgroundColor = UIColor.clear // added a transparent background to the view

        if isAnimating{

            uiView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0);// start at full scale

            let startPoint = CGPoint(x: 250, y: 500)
            let apexPoint = CGPoint(x: 100 + 50, y: 50 - 200)
            let endPoint = CGPoint(x: 25, y: -100) // Fixed the end point to hit target
            let durationTime = 0.8

            let path = UIBezierPath()
            path.move(to: startPoint)
            path.addQuadCurve(to: endPoint, controlPoint: apexPoint)

            CATransaction.begin() // to be able to capture the beggining of the animation
            CATransaction.setCompletionBlock({
//                print("Animation completed!")
                uiView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            })
            let animation = CAKeyframeAnimation(keyPath: "position")
            animation.path = path.cgPath
            animation.duration = durationTime
            uiView.layer.add(animation, forKey: "bezier")
            uiView.center = endPoint

            UIView.animate(withDuration: durationTime, animations: {
                uiView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5);
            })

            CATransaction.commit() // to be able to capture the end of the animation

        }
        isAnimating = false // added so you dont have to double click for the animation
    }

3      

Oh shoot, something so simple, you're my hero. Thank you for the extra improvements; I had to move the isAnimating = false inside the setCompletionBlock since I was getting a purple warning, good point to set it to false after the animation is done.

Quick question, how hard would it be to make the endPoint location dynamic? In other words, reference other views' x and y locaiton as the endPoint, for when in bigger/smaller screens.

Thanks a LOT!

2      

Well as far as bigger/smaller screens i tried it with the iPad simulator and it was still hitting the target, the starting point on the other hand was moving around depending on the screen size to fix it just add this line

let startPoint = CGPoint(x: uiView.frame.width / 2, y: uiView.frame.height / 2)

now if you add or remove views thats another problem, maybe you can try to get the targets position using a geometry reader but im not sure how to do it.

3      

You're right, the target is hit regardless of screen size, wow, I didn't try that until now. Thanks a lot for your help, it really helped a lot!

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.