I have two Rectangles, Rectangle A and Rectangle B. Rectangle A will move horizontally, and the center point of A will align with the top left corner of B in the horizontal direction. B will rotate around its own center point.
I have some code but I don't know how to writing next. How can I use alignmentGuide
and PreferenceKey
to achieve this animation?
struct MyAnchorKey: PreferenceKey {
static var defaultValue: Anchor<CGPoint>? = nil
static func reduce(value: inout Anchor<CGPoint>?, nextValue: () -> Anchor<CGPoint>?) {
value = value ?? nextValue()
}
}
struct ContentView: View {
@State private var rotationAngle: Double = 0
var body: some View {
VStack(spacing: 50) {
// Rectangle A
Rectangle()
.fill(Color.blue)
.frame(width: 50, height: 50)
// How to use alignmentGuide to align the center point with the top left corner of B
// Rectangle B
Rectangle()
.fill(Color.gray)
.frame(width: 200, height: 50)
.rotationEffect(.degrees(rotationAngle))
.animation(Animation.linear(duration: 3).repeatForever(autoreverses: false))
// How to use anchorPreference to record top leading position
}
.onAppear {
rotationAngle = 360
}
}
}