Created
May 9, 2020 19:48
-
-
Save rayfix/605066823f4a70c644dd216226d51c41 to your computer and use it in GitHub Desktop.
make views draggable
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
// | |
// 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