Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
make views draggable
//
// ContentView.swift
//
// Created by Ray Fix on 5/9/20.
// Copyright © 2020 Ray Fix. All rights reserved.
//
import SwiftUI
struct ContentView: View {
func card(_ color: Color) -> some View {
Rectangle()
.foregroundColor(color)
.frame(width: 100, height: 130)
.cornerRadius(5)
}
var body: some View {
HStack {
card(.green)
card(.red)
}
}
}
extension View {
func draggable() -> some View {
modifier(DraggingModifier())
}
}
struct DraggingModifier: ViewModifier {
@GestureState private var isDragging = false
@GestureState private var dragOffset: CGSize = .zero
var dragGesture: some Gesture {
DragGesture()
.updating($isDragging) { (value, state, transaction) in
state = true
}
.updating($dragOffset) { (value, state, transaction) in
state = value.translation
}
}
func body(content: Content) -> some View {
content
.rotationEffect(Angle(degrees: isDragging ? 5:0))
.animation(.default)
.offset(dragOffset)
.zIndex(isDragging ? 1 : 0)
.gesture(dragGesture)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment