-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcustom_refresh_view.swift
246 lines (216 loc) · 8.94 KB
/
custom_refresh_view.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//
// CustomRefreshView.swift
// whatsgoingon
//
// Created by Fabian Gruß on 13.10.2023.
//
import SwiftUI
// Usage:
/*
CustomRefreshView(showsIndicator: false) {
# Add content here that should be pulled down
} onRefresh: {
# Do something here, i.e. refresh or open something
# It's possible to add a waiting state: try? await Task.sleep(nanoseconds: 1000000000)
}
*/
struct CustomRefreshView<Content: View>: View {
var content: Content
var showsIndicator: Bool
var onRefresh: () async->()
init(showsIndicator: Bool = false, @ViewBuilder content: @escaping ()->Content, onRefresh: @escaping () async->()) {
self.showsIndicator = showsIndicator
self.content = content()
self.onRefresh = onRefresh
}
@StateObject var scrollDelegate: ScrollViewModel = .init()
var body: some View {
ScrollView(.vertical, showsIndicators: showsIndicator) {
VStack(spacing: 0) {
GeometryReader { _ in
HStack {
// Keep it centered
Spacer()
CustomProgressView(progress: scrollDelegate.progress)
Spacer()
}
.opacity(scrollDelegate.isEligible ? 0 : 1)
.animation(.easeInOut(duration: 0.25), value: scrollDelegate.isEligible)
.frame(height: 200)
.opacity(scrollDelegate.progress)
.offset(y: scrollDelegate.isEligible ? -(scrollDelegate.contentOffset < 0 ? 0 : scrollDelegate.contentOffset) : -(scrollDelegate.scrollOffset < 0 ? 0 : scrollDelegate.scrollOffset))
}
.frame(height: 0)
.offset(y: -75 + (75 * scrollDelegate.progress))
content
.offset(y: scrollDelegate.progress * 100)
}
.offset(coordinateSpace: "SCROLL") { offset in
scrollDelegate.contentOffset = offset
// Checking if refresh action should be triggered
if !scrollDelegate.isEligible {
var progress = offset / 100
progress = (progress < 0 ? 0 : progress)
progress = (progress > 1 ? 1 : progress)
scrollDelegate.scrollOffset = offset
scrollDelegate.progress = progress
// Additional haptic feedback if needed
if progress >= 0.75 && !scrollDelegate.vibrateAt75 {
// UIImpactFeedbackGenerator(style: .medium).impactOccurred()
scrollDelegate.vibrateAt75 = true
} else if progress >= 0.05 && !scrollDelegate.vibrateAt50 {
UIImpactFeedbackGenerator(style: .medium).impactOccurred()
scrollDelegate.vibrateAt50 = true
} else if progress >= 0.25 && !scrollDelegate.vibrateAt25 {
// UIImpactFeedbackGenerator(style: .soft).impactOccurred()
scrollDelegate.vibrateAt25 = true
}
}
// Additional haptic feedback at "success"
if scrollDelegate.isEligible && !scrollDelegate.isRefreshing {
scrollDelegate.isRefreshing = true
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
}
}
}
.coordinateSpace(name: "SCROLL")
.onAppear(perform: scrollDelegate.addGesture)
.onDisappear(perform: scrollDelegate.removeGesture)
.onChange(of: scrollDelegate.isRefreshing) {
if scrollDelegate.isRefreshing {
scrollDelegate.vibrateAt25 = false
scrollDelegate.vibrateAt50 = false
scrollDelegate.vibrateAt75 = false
Task {
// Trigger refresh action
await onRefresh()
withAnimation(.easeInOut(duration: 0.25)) {
scrollDelegate.progress = 0
scrollDelegate.isEligible = false
scrollDelegate.isRefreshing = false
scrollDelegate.scrollOffset = 0
}
}
}
}
}
}
// Previews if needed
struct CustomRefreshView_Previews: PreviewProvider {
static var previews: some View {
CustomRefreshView(showsIndicator: false) {
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200)
} onRefresh: {
try? await Task.sleep(nanoseconds: 1000000000)
}
}
}
class ScrollViewModel: NSObject, ObservableObject, UIGestureRecognizerDelegate {
// MARK: Properties
@Published var isEligible: Bool = false
@Published var isRefreshing: Bool = false
// MARK: Gesture Properties
@Published var scrollOffset: CGFloat = 0
@Published var contentOffset: CGFloat = 0
@Published var progress: CGFloat = 0
let gestureID: String = UUID().uuidString
// MARK: Haptic Feedback Properties
@Published var vibrateAt25: Bool = false
@Published var vibrateAt50: Bool = false
@Published var vibrateAt75: Bool = false
// Adding Pan Gesture To UI Main Application Window
// With Simultaneous Gesture Desture
// Thus it Wont disturb SwiftUI Scroll's And Gesture's
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer)->Bool {
return true
}
// MARK: Adding Gesture
func addGesture() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onGestureChange(gesture:)))
panGesture.delegate = self
panGesture.name = gestureID
rootController().view.addGestureRecognizer(panGesture)
}
// MARK: Removing When Leaving The View
func removeGesture() {
rootController().view.gestureRecognizers?.removeAll(where: { gesture in
gesture.name == gestureID
})
}
// MARK: Finding Root Controller
func rootController()->UIViewController {
guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
return .init()
}
guard let root = screen.windows.first?.rootViewController else {
return .init()
}
return root
}
@objc
func onGestureChange(gesture: UIPanGestureRecognizer) {
if gesture.state == .cancelled || gesture.state == .ended {
// User released touch here
if !isRefreshing {
if scrollOffset > 100 {
isEligible = true
} else {
isEligible = false
}
}
}
}
}
// Extension to observe changes in the offset of a view
extension View {
@ViewBuilder
func offset(coordinateSpace: String, offset: @escaping (CGFloat)->())->some View {
overlay {
GeometryReader { proxy in
let minY = proxy.frame(in: .named(coordinateSpace)).minY
Color.clear
.preference(key: RefreshOffsetKey.self, value: minY)
.onPreferenceChange(RefreshOffsetKey.self) { value in
offset(value)
}
}
}
}
}
// A preference key used to store the minimum Y offset of a view
struct RefreshOffsetKey: PreferenceKey {
static var defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: ()->CGFloat) {
value = nextValue()
}
}
// Your custom view that is shown when the user pulls down. Gets a progress value from 0 to 1.
struct CustomProgressView: View {
var progress: CGFloat
var body: some View {
VStack(spacing: 12) {
ZStack {
Circle()
.stroke(.clear.opacity(0.2), lineWidth: 5)
.frame(width: 50, height: 50)
Circle()
.trim(from: 0, to: progress)
.stroke(.accentColorPrimary, style: StrokeStyle(lineWidth: 5, lineCap: .round))
.rotationEffect(.degrees(-90))
.frame(width: 50, height: 50)
.shadow(color: Color(red: 0.48, green: 0.57, blue: 1).opacity(0.4), radius: 4, x: 0, y: 3)
// V1 with simple plus
/* Image(systemName: "plus")
.font(.system(size: 16 * (0.6 + progress), weight: .semibold))
.foregroundColor(.accentColorPrimary).opacity((0.3 + progress) > 1 ? 1 : (0.3 + progress)) */
// Var 2: Filled
Image(systemName: "plus.circle.fill")
.font(.system(size: 32 * (0.6 + progress)))
.foregroundColor(.accentColorPrimary).opacity((0.6 + progress) > 1 ? 1 : (0.6 + progress))
}
Text("Pull to add update").contentSubtitle()
}
}
}