Hello guys! Can I attach one object to another using a magnate animation in SwiftUI? For example In the code below I want the blue square to attach with the red one, when I drag it near it.
Here's. my code:
import PlaygroundSupport
import SwiftUI
struct ContentView: View {
@State private var isDragging = false
@State private var dragOffset: CGSize = .zero
@State var position: CGSize = .zero
@State private var hovered = false
var body: some View {
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.red)
.frame(width: 100, height: 100)
.position(x: 400, y: 350)
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.blue)
.frame(width: 100, height: 100)
.position(x: 400, y: 350)
.animation(.default, value: hovered)
.offset(x: dragOffset.width + position.width, y: dragOffset.height + position.height)
.gesture(
DragGesture()
.onChanged({ value in
self.dragOffset = value.translation
})
.onEnded({ value in
self.position.width += value.translation.width
self.position.height += value.translation.height
self.dragOffset = .zero
})
)
}
}
PlaygroundPage.current.setLiveView(ContentView())
If anyone knows how to do this, please help me.
Thanks