Last active
October 15, 2024 19:59
-
-
Save rnmp/920b08548cc45a1ebdd3547eef8f4490 to your computer and use it in GitHub Desktop.
Draggable floating panel in SwiftUI. See use case: https://youtu.be/10Ee-BAxGug
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 | |
// Generated using ChatGPT 4o | |
// Prompts: | |
// - "How to quickly make a panel using SwiftUI on macOS that can be dragged around inside a window?" | |
// - "Let's make it take content as closure" | |
struct DraggablePanel<Content: View>: View { | |
@State private var offset = CGSize.zero | |
@State private var dragOffset = CGSize.zero | |
let content: () -> Content | |
var body: some View { | |
VStack { | |
content() | |
} | |
.frame(width: 200, height: 500) | |
.background(RoundedRectangle(cornerRadius: 10).fill(.black).opacity(0.7).shadow(radius: 8)) | |
.offset(x: offset.width + dragOffset.width, y: offset.height + dragOffset.height) | |
.gesture( | |
DragGesture() | |
.onChanged { gesture in | |
dragOffset = gesture.translation | |
} | |
.onEnded { _ in | |
offset.width += dragOffset.width | |
offset.height += dragOffset.height | |
dragOffset = .zero | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment