Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created May 9, 2020 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayfix/605066823f4a70c644dd216226d51c41 to your computer and use it in GitHub Desktop.
Save rayfix/605066823f4a70c644dd216226d51c41 to your computer and use it in GitHub Desktop.
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