Last active
July 1, 2020 17:44
-
-
Save brunogb/5a2c63cbf2ab2a9d2cfc3b40969479fb to your computer and use it in GitHub Desktop.
Drag'n'Drop with SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import PlaygroundSupport | |
struct MyView: View { | |
@State var viewOffset: CGSize = .zero { | |
didSet { | |
let newFrame = viewFrame.offsetBy(dx: self.viewOffset.width, dy: self.viewOffset.height) | |
self.canDrop = containerFrame.intersects(newFrame) | |
} | |
} | |
@State var containerFrame: CGRect = .zero | |
@State var viewFrame: CGRect = .zero { | |
didSet { | |
print("View frame: \(self.viewFrame)") | |
} | |
} | |
@State var canDrop: Bool = false | |
var body: some View { | |
VStack { | |
VStack { | |
Text( canDrop ? "Drop view here": "You cant drop here") | |
} | |
.background(canDrop ? Color.yellow : Color.blue) | |
.overlay(GeometryReader { r in | |
Color.clear | |
.onAppear { | |
self.containerFrame = r.frame(in: .global) | |
print("\(self.containerFrame)") | |
} | |
}) | |
HStack { | |
Text("Drag me") | |
} | |
.overlay(GeometryReader { r in | |
Color.clear | |
.onAppear { | |
self.viewFrame = r.frame(in: .global) | |
} | |
}) | |
.background(Color.white) | |
.offset(viewOffset) | |
.gesture(DragGesture(coordinateSpace: .global).onChanged({ (value) in | |
self.viewOffset = value.translation | |
}).onEnded({ (value) in | |
self.viewOffset = .zero | |
})) | |
} | |
} | |
} | |
let controller = UIHostingController(rootView: MyView()) | |
PlaygroundPage.current.liveView = controller |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment