forked from djayyab/-IOS-App-IEEEMadC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSBCardPopupViewController.swift
509 lines (389 loc) · 16.3 KB
/
SBCardPopupViewController.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//
// SBCardPopupViewController.swift
//
//
// Created by dodo on 7/10/19.
//
import UIKit
public protocol SBCardPopupContent: class {
weak var popupViewController: SBCardPopupViewController? {get set}
var allowsTapToDismissPopupCard: Bool {get}
var allowsSwipeToDismissPopupCard: Bool {get}
}
public class SBCardPopupViewController: UIViewController {
// MARK: - Public Interface
public var disableSwipeToDismiss = false
public var disableTapToDismiss = false
public var cornerRadius = CGFloat(7)
public init(contentViewController viewController: UIViewController) {
contentViewController = viewController
contentView = viewController.view
super.init(nibName: nil, bundle: nil)
}
public init(contentView view: UIView) {
contentViewController = nil
contentView = view
super.init(nibName: nil, bundle: nil)
}
public func close() {
animateOut()
}
public func show(onViewController viewController: UIViewController) {
self.modalPresentationStyle = .overCurrentContext
viewController.present(self, animated: false, completion: nil)
}
// MARK: - Types
enum State {
case animatingIn
case idle
case panning
case animatingOut
case physicsOut(PhysicsState)
}
struct PhysicsState {
let acceleration = CGFloat(9999)
var velocity = CGFloat(0)
}
// MARK: - Properties
private let backgroundOpacity = CGFloat(0.6)
private var displayLink: CADisplayLink!
private var lastTimeStamp: CFTimeInterval?
private let contentViewController: UIViewController?
private let contentView: UIView
fileprivate let containerView = UIView(frame: .zero)
private var hasAnimatedIn = false
private var containerCenterYConstraint: NSLayoutConstraint!
private var containerOffscreenConstraint: NSLayoutConstraint!
fileprivate var tapRecognizer: UITapGestureRecognizer!
fileprivate var panRecognizer: UIPanGestureRecognizer!
private var swipeOffset = CGFloat(0)
fileprivate var popupProtocolResponder: SBCardPopupContent? {
if let contentViewController = contentViewController {
if let protocolResponder = contentViewController as? SBCardPopupContent {
return protocolResponder
}
}
else if let protocolResponder = contentView as? SBCardPopupContent {
return protocolResponder
}
return nil
}
private var state = State.animatingIn
// MARK: - UIViewController
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
// Container view
containerView.layer.cornerRadius = cornerRadius
containerView.layer.masksToBounds = true
view.addSubview(containerView)
containerView.isUserInteractionEnabled = false
// Content
if let contentViewController = contentViewController {
addChild(contentViewController)
}
containerView.addSubview(contentView)
// Popup Protocol Responder
popupProtocolResponder?.popupViewController = self
// Apply Constraints
applyContainerViewConstraints()
applyContentViewConstraints()
containerOffscreenConstraint.isActive = true
// Tap Away Recognizer
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAway))
tapRecognizer.delegate = self
view.addGestureRecognizer(tapRecognizer)
// Pan Recognizer
panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan))
panRecognizer.delegate = self
view.addGestureRecognizer(panRecognizer)
// Display Link
// displayLink = CADisplayLink(target: self, selector: #selector(tick))
// displayLink.add(to: .current, forMode: .RunLoop.Mode.common)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !hasAnimatedIn {
animateIn()
hasAnimatedIn = true
}
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
displayLink.invalidate()
}
public override func updateViewConstraints() {
super.updateViewConstraints()
// Elastic Pull upwards
if swipeOffset < 0 {
let offset = -swipeOffset
let offsetPct = (offset / view.bounds.size.width/2)
let elasticity = CGFloat(3)
let percent = offsetPct / (1.0 + (offsetPct * elasticity))
containerCenterYConstraint.constant = -(percent * view.bounds.size.width/2)
}
// Regular tracking downwards
else{
containerCenterYConstraint.constant = swipeOffset
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Update background color and card opacity if panning or physics out
switch state {
case .animatingIn: break
case .idle: break
case .animatingOut: break
case .panning: fallthrough
case .physicsOut:
let distance = view.bounds.size.height/2 + contentView.frame.size.height/2
var outPct = 1.0 - (swipeOffset / distance)
outPct = min(outPct, 1.0)
let opacity = backgroundOpacity * outPct
view.backgroundColor = UIColor(white: 0, alpha: opacity)
containerView.alpha = outPct
}
}
// MARK: - Constraints
private func applyContentViewConstraints() {
contentView.translatesAutoresizingMaskIntoConstraints = false
[NSLayoutConstraint.Attribute.left, .right, .top, .bottom].forEach{
let constraint = NSLayoutConstraint(item: contentView,
attribute: $0,
relatedBy: .equal,
toItem: containerView,
attribute: $0,
multiplier: 1.0,
constant: 0)
containerView.addConstraint(constraint)
}
}
private func applyContainerViewConstraints() {
containerView.translatesAutoresizingMaskIntoConstraints = false
let sideMargin = CGFloat(20)
let verticalMargins = CGFloat(20)
let left = NSLayoutConstraint(item: containerView,
attribute: .left,
relatedBy: .equal,
toItem: view,
attribute: .left,
multiplier: 1.0,
constant: sideMargin)
let right = NSLayoutConstraint(item: containerView,
attribute: .right,
relatedBy: .equal,
toItem: view,
attribute: .right,
multiplier: 1.0,
constant: -sideMargin)
containerCenterYConstraint = NSLayoutConstraint(item: containerView,
attribute: .centerY,
relatedBy: .equal,
toItem: view,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
containerCenterYConstraint.priority = UILayoutPriority.defaultLow
let limitHeight = NSLayoutConstraint(item: containerView,
attribute: .height,
relatedBy: .lessThanOrEqual,
toItem: view,
attribute: .height,
multiplier: 1.0,
constant: -verticalMargins*2)
limitHeight.priority = UILayoutPriority.defaultHigh
containerOffscreenConstraint = NSLayoutConstraint(item: containerView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0)
containerOffscreenConstraint.priority = UILayoutPriority.required
view.addConstraints([left, right, containerCenterYConstraint, limitHeight, containerOffscreenConstraint])
}
private func pinContainerOffscreen(_ pinOffscreen: Bool) {
containerOffscreenConstraint.isActive = pinOffscreen
}
// MARK: - Animation
private func animateIn() {
let duration = 0.49
// Animate background color
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut, .allowUserInteraction],
animations: {
self.view.backgroundColor = UIColor(white: 0, alpha: self.backgroundOpacity)
}, completion: nil)
// Animate container on screen
containerOffscreenConstraint.isActive = false
self.view.setNeedsUpdateConstraints()
UIView.animate(withDuration: duration,
delay: 0.0,
usingSpringWithDamping: 0.84,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: {
self.view.layoutIfNeeded()
}, completion: {
_ in
self.containerView.isUserInteractionEnabled = true
self.state = .idle
})
}
private func animateOut() {
view.isUserInteractionEnabled = false
state = .animatingOut
let duration = 0.6
// Animate background color
UIView.animate(withDuration: duration,
delay: 0.0,
options: [.curveEaseInOut],
animations: {
self.view.backgroundColor = UIColor.clear
}, completion: nil)
// Animate container off screen
containerOffscreenConstraint.isActive = true
view.setNeedsUpdateConstraints()
UIView.animate(withDuration: duration,
delay: 0.0,
usingSpringWithDamping: 0.8,
initialSpringVelocity: 0,
options: [],
animations: {
self.view.layoutIfNeeded()
}, completion: {
_ in
self.dismiss(animated: false, completion: nil)
})
}
private func animate(fromPan panRecognizer: UIPanGestureRecognizer) {
let animateOutThreshold = CGFloat(50)
let velocity = panRecognizer.velocity(in: view).y
// Animate out
if velocity > animateOutThreshold {
let physicsState = PhysicsState(velocity: velocity)
state = .physicsOut(physicsState)
}
// Snap back
else {
animateSnapBackToCenter()
}
}
private func animateSnapBackToCenter() {
let duration = 0.4
swipeOffset = 0
view.setNeedsUpdateConstraints()
//view.setNeedsLayout()
UIView.animate(withDuration: duration,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: {
self.view.layoutIfNeeded()
}, completion: { _ in })
}
// MARK: - Gestures
@objc private func tapAway() {
if let protocolResponder = popupProtocolResponder {
if protocolResponder.allowsTapToDismissPopupCard {
animateOut()
}
}
else{
animateOut()
}
}
@objc private func didPan(recognizer: UIPanGestureRecognizer) {
if state == .animatingIn {
state = .idle
self.view.layer.removeAllAnimations()
self.containerView.layer.removeAllAnimations()
}
guard
state == .idle || state == .panning
else { return }
let applyOffset = {
self.swipeOffset = recognizer.translation(in: self.view).y
self.view.setNeedsUpdateConstraints()
}
switch recognizer.state {
case .possible:
break
case .began:
state = .panning
applyOffset()
case .changed:
state = .panning
applyOffset()
case .cancelled:
break
case .failed:
break
case .ended:
animate(fromPan: recognizer)
}
}
// MARK: - Display Link
@objc func tick() {
// We need a previous time stamp to work with, bail if we don't have one
guard let last = lastTimeStamp else {
lastTimeStamp = displayLink.timestamp
return
}
// Work out dt
let dt = displayLink.timestamp - last
// Save the current time
lastTimeStamp = displayLink.timestamp
// If we're using physics to animate out, update the simulation
guard case var State.physicsOut(physicsState) = state else {
return
}
physicsState.velocity += CGFloat(dt) * physicsState.acceleration
swipeOffset += physicsState.velocity * CGFloat(dt)
view.setNeedsUpdateConstraints()
state = .physicsOut(physicsState)
// Remove if the content view is off screen
if swipeOffset > view.bounds.size.height / 2 {
dismiss(animated: false, completion: nil)
}
}
}
extension SBCardPopupViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// Pan, check if swipe enabled
if let responder = popupProtocolResponder, gestureRecognizer === panRecognizer {
if self.disableSwipeToDismiss {
return false
}
return responder.allowsSwipeToDismissPopupCard
}
// Tap, check if is outside view
if gestureRecognizer === tapRecognizer {
if self.disableTapToDismiss {
return false
}
let location = tapRecognizer.location(in: view)
return !containerView.frame.contains(location)
}
return true
}
}
func ==(lhs: SBCardPopupViewController.State, rhs: SBCardPopupViewController.State) -> Bool {
switch (lhs, rhs) {
case (.animatingIn, .animatingIn):
return true
case (.idle, .idle):
return true
case (.panning, .panning):
return true
case (.physicsOut, .physicsOut):
return true
default:
return false
}
}