Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix Rectangle to it's position to prevent it from randomly flying around the screen after rotation of device?

I need to have working rotation animation and the rectangle on the same relative position after changing orientation. Right now the rectangle starts randomly fly around the screen after change orientation of device.

import SwiftUI

struct ContentView: View {
    @State private var isAnimating = false
    var animation: Animation {
        Animation.linear(duration: 1)
            .repeatForever(autoreverses: false)
    }
    
    var body: some View {
        HStack {
            Text("Hello, world!")
                .padding()
            Spacer()
            Rectangle()
                .frame(width: 20, height: 20)
                .foregroundColor(.red)
                .rotationEffect(Angle.degrees(isAnimating ? 360 : 0))
                .animation(animation)
                .onAppear {
                    isAnimating = true
                }
        }
    }
}

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You just need to join animation with value, like

Rectangle()
    .frame(width: 20, height: 20)
    .foregroundColor(.red)
    .rotationEffect(Angle.degrees(isAnimating ? 360 : 0))
    .animation(animation, value: isAnimating)             // << here !!
    .onAppear {
        isAnimating = true
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading