-
Notifications
You must be signed in to change notification settings - Fork 0
/
DragGestureBootcamp.swift
121 lines (107 loc) · 3.59 KB
/
DragGestureBootcamp.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//
// DragGestureBootcamp.swift
// SwiftfulThinkingBootcamp
//
// Created by enesozmus on 14.05.2024.
//
import SwiftUI
struct DragGestureBootcamp: View {
// ... ⬛️
// MARK: PROPERTIES
@State private var isDragging: Bool = false
var drag: some Gesture {
DragGesture()
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
@State private var offset: CGSize = .zero
// ... ⬛️
// MARK: BODY
var body: some View {
// ... 🟦
Circle()
.fill(self.isDragging ? Color.red : Color.blue)
.frame(width: 100, height: 100, alignment: .center)
.gesture(drag)
// ... 🟦
RoundedRectangle(cornerRadius: 12.0)
.frame(width: 100, height: 100)
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in
withAnimation(.spring) {
offset = value.translation
}
}
.onEnded { value in
withAnimation(.spring) {
offset = .zero
}
}
)
// ... 🟦
ZStack {
VStack {
Text("\(offset.width)")
Spacer()
}
RoundedRectangle(cornerRadius: 12.0)
.frame(width: 300, height: 500)
.offset(offset)
.scaleEffect(getScaleAmount())
.rotationEffect(Angle(degrees: getRotationAmount()))
.gesture(
DragGesture()
.onChanged { value in
withAnimation(.spring) {
offset = value.translation
}
}
.onEnded { value in
withAnimation(.spring) {
offset = .zero
}
}
)
}
}
// ... ⬛️
// MARK: FUNCTIONS
func getScaleAmount() -> CGFloat {
let max = UIScreen.main.bounds.width / 2
let currentAmount = abs(offset.width)
let percentage = currentAmount / max
return 1.0 - min(percentage, 0.5) * 0.5
}
func getRotationAmount() -> Double {
let max = UIScreen.main.bounds.width / 2
let currentAmount = offset.width
let percentage = currentAmount / max
let percentageAsDouble = Double(percentage)
let maxAngle: Double = 10.0
return percentageAsDouble * maxAngle
}
}
#Preview {
DragGestureBootcamp()
}
/*
🔴 DragGesture
→ A dragging motion that invokes an action as the drag-event sequence changes.
→ To recognize a drag gesture on a view, create and configure the gesture, and then add it to the view using the gesture(_:including:) modifier.
struct DragGestureView: View {
@State private var isDragging = false
var drag: some Gesture {
DragGesture()
.onChanged { _ in self.isDragging = true }
.onEnded { _ in self.isDragging = false }
}
var body: some View {
Circle()
.fill(self.isDragging ? Color.red : Color.blue)
.frame(width: 100, height: 100, alignment: .center)
.gesture(drag)
}
}
*/