This repository has been archived by the owner on Feb 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
PullToDismissTransition.swift
494 lines (393 loc) · 18.2 KB
/
PullToDismissTransition.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
//
// PullToDismissTransition.swift
// PullToDismissTransition
//
// Created by Ben Guild on 2018/06/14.
// Copyright © 2018年 Ben Guild. All rights reserved.
//
import UIKit
public protocol PullToDismissTransitionDelegate: class {
func canBeginPullToDismiss(on dismissingViewController: UIViewController) -> Bool
func didBeginPullToDismissAttempt(on dismissingViewController: UIViewController)
func didCompletePullToDismissAttempt(on dismissingViewController: UIViewController, willDismiss: Bool)
func didFinishTransition(for dismissingViewController: UIViewController, didDismiss: Bool)
}
extension PullToDismissTransitionDelegate {
public func canBeginPullToDismiss(on dismissingViewController: UIViewController) -> Bool {
return true
}
public func didBeginPullToDismissAttempt(on dismissingViewController: UIViewController) {}
public func didCompletePullToDismissAttempt(on dismissingViewController: UIViewController, willDismiss: Bool) {}
public func didFinishTransition(for dismissingViewController: UIViewController, didDismiss: Bool) {}
}
public enum PullToDismissTransitionType {
case slideStatic
case slideDynamic
case scale
}
public class PullToDismissTransition: UIPercentDrivenInteractiveTransition {
private struct Const {
static let dimmingAlphaTransitionFinishDropDelay: TimeInterval = 0.24
static let dimmingPeakAlpha: CGFloat = 0.87
static let minimumTranslationYForDismiss: CGFloat = 87
static let translationThreshold: CGFloat = 0.35
static let scalingViewCornerRadius: CGFloat = 12
static let scalingViewCornerRadiusToggleDuration: TimeInterval = 0.15
static let scalingPeakScaleDivider: CGFloat = 5
static let touchStillWithoutPanEndDelay: TimeInterval = 0.15
static let transitionDurationDragSlide: TimeInterval = 0.87
static let transitionDurationDragScale: TimeInterval = 0.35
static let transitionReEnableTimeoutAfterScroll: TimeInterval = 0.72
static let velocityBeginThreshold: CGFloat = 10
static let velocityFinishThreshold: CGFloat = 1280
}
public let transitionType: PullToDismissTransitionType
public let animationOptions: UIView.AnimationOptions
private(set) weak var viewController: UIViewController?
private(set) weak var monitoredScrollView: UIScrollView?
public var permitWhenNotAtRootViewController = false
public weak var delegate: PullToDismissTransitionDelegate?
public var isDimmingEnabled = true
private weak var dimmingView: UIView?
private weak var scalingView: UIView?
private var transitionIsActiveFromTranslationPoint: CGPoint?
private var didRequestScrollViewBounceDisable = false
private var monitoredScrollViewDoesBounce = false
private var recentScrollIsBlockingTransition = false
private var scrollInitiateCount: Int = 0
private var scrollViewObservation: NSKeyValueObservation?
private var touchBeginOrPanIncrement: Int = 0
private var transitionHasEndedAndPanIsInactive = false
private var currentTouchIsStillAndActive = false
private var mostRecentActiveGestureTranslation: CGPoint?
@objc dynamic public private(set) var transitionProgress: CGFloat = 0
public var transitionDelegateObservation: NSKeyValueObservation?
deinit {
scrollViewObservation?.invalidate()
transitionDelegateObservation?.invalidate()
}
public init(
viewController: UIViewController,
animationOptions: UIView.AnimationOptions = [.curveLinear],
transitionType: PullToDismissTransitionType = .slideStatic
) {
self.animationOptions = animationOptions
self.transitionType = transitionType
self.viewController = viewController
super.init()
}
public func additionalGestureRecognizerForTrigger() -> UIGestureRecognizer {
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan))
panGestureRecognizer.delegate = self
return panGestureRecognizer
}
private func updateBounceLockoutState() {
guard let monitoredScrollView = monitoredScrollView else { return }
guard monitoredScrollViewDoesBounce else { return }
var doesTranslateY = false
switch transitionType {
case .slideStatic, .slideDynamic:
doesTranslateY = true
case .scale:
doesTranslateY = false
}
let shouldScrollViewBounceBeDisabled =
currentTouchIsStillAndActive ||
((mostRecentActiveGestureTranslation?.y ?? 0) > 0) ||
(doesTranslateY && transitionHasEndedAndPanIsInactive && monitoredScrollView.contentOffset.y <= 0)
guard shouldScrollViewBounceBeDisabled != didRequestScrollViewBounceDisable else { return }
didRequestScrollViewBounceDisable = shouldScrollViewBounceBeDisabled
guard monitoredScrollView.bounces != !shouldScrollViewBounceBeDisabled else { return }
monitoredScrollView.bounces = !shouldScrollViewBounceBeDisabled
}
public func monitorActiveScrollView(scrollView: UIScrollView) {
if let monitoredScrollView = monitoredScrollView, monitoredScrollViewDoesBounce {
monitoredScrollView.bounces = true
}
scrollViewObservation?.invalidate()
monitoredScrollView = scrollView
didRequestScrollViewBounceDisable = false
monitoredScrollViewDoesBounce = scrollView.bounces
recentScrollIsBlockingTransition = false
scrollViewObservation = scrollView.observe(
\UIScrollView.contentOffset,
options: [.initial, .new]
) { [weak self] scrollView, _ in
self?.updateBounceLockoutState()
guard scrollView.contentOffset.y > scrollView.bounds.size.height else { return }
self?.recentScrollIsBlockingTransition = true
self?.scrollInitiateCount += 1
let localCopyOfScrollInitiateCount = self?.scrollInitiateCount
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Const.transitionReEnableTimeoutAfterScroll
) {
guard self?.monitoredScrollView === scrollView else { return }
guard self?.scrollInitiateCount == localCopyOfScrollInitiateCount else { return }
self?.recentScrollIsBlockingTransition = false
}
}
}
private func isAtRootViewController() -> Bool {
guard let navigationController = (viewController as? UINavigationController)
?? viewController?.navigationController else { return true }
return (navigationController.viewControllers.count <= 1)
}
private func canBeginPullToDismiss(
velocity: CGPoint = .zero,
on viewController: UIViewController
) -> Bool {
return !recentScrollIsBlockingTransition &&
velocity.y > Const.velocityBeginThreshold &&
velocity.y > abs(velocity.x) &&
(permitWhenNotAtRootViewController || isAtRootViewController()) &&
(monitoredScrollView?.contentOffset.y ?? 0) <= 0 &&
(delegate?.canBeginPullToDismiss(on: viewController) ?? true)
}
private func stopPullToDismiss(on viewController: UIViewController, finished: Bool) {
if finished {
finish()
} else {
cancel()
}
guard transitionIsActiveFromTranslationPoint != nil else { return }
transitionIsActiveFromTranslationPoint = nil
delegate?.didCompletePullToDismissAttempt(on: viewController, willDismiss: finished)
}
private func handlePan(from panGestureRecognizer: UIPanGestureRecognizer, on view: UIView) {
guard let viewController = viewController else { return }
let translation = panGestureRecognizer.translation(in: view)
let velocity = panGestureRecognizer.velocity(in: view)
currentTouchIsStillAndActive = false
touchBeginOrPanIncrement += 1
switch panGestureRecognizer.state {
case .began, .changed:
mostRecentActiveGestureTranslation = translation
transitionHasEndedAndPanIsInactive = false
if let transitionIsActiveFromTranslationPoint = transitionIsActiveFromTranslationPoint {
let progress = min(1, max(
0,
(translation.y - transitionIsActiveFromTranslationPoint.y) / max(1, view.bounds.size.height)
))
if progress == 0 {
stopPullToDismiss(on: viewController, finished: false)
break
}
transitionProgress = progress
update(progress)
} else if canBeginPullToDismiss(velocity: velocity, on: viewController) {
transitionIsActiveFromTranslationPoint = translation
if let monitoredScrollView = monitoredScrollView, monitoredScrollView.isScrollEnabled {
monitoredScrollView.contentOffset = CGPoint(
x: monitoredScrollView.contentOffset.x - monitoredScrollView.contentInset.left,
y: -monitoredScrollView.contentInset.top
)
}
viewController.dismiss(animated: true) { [weak self] in
let didDismiss = (viewController.presentingViewController == nil)
if didDismiss {
self?.transitionDelegateObservation?.invalidate()
}
self?.delegate?.didFinishTransition(for: viewController, didDismiss: didDismiss)
}
delegate?.didBeginPullToDismissAttempt(on: viewController)
}
case .cancelled, .ended:
if transitionIsActiveFromTranslationPoint != nil {
transitionHasEndedAndPanIsInactive = true
}
mostRecentActiveGestureTranslation = nil
stopPullToDismiss(on: viewController, finished: panGestureRecognizer.state != .cancelled && (
(percentComplete >= Const.translationThreshold && velocity.y >= 0) ||
(
velocity.y >= Const.velocityFinishThreshold &&
translation.y >= Const.minimumTranslationYForDismiss
)
))
default:
break
}
updateBounceLockoutState()
}
@objc private func didPan(sender: Any?) {
guard let panGestureRecognizer = sender as? UIPanGestureRecognizer else { return }
guard let view = panGestureRecognizer.view else { return }
handlePan(from: panGestureRecognizer, on: view)
}
}
extension PullToDismissTransition: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
touchBeginOrPanIncrement += 1
currentTouchIsStillAndActive = true
let localCopyOfTouchBeginOrPanIncrement = touchBeginOrPanIncrement
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Const.touchStillWithoutPanEndDelay) {
guard self.touchBeginOrPanIncrement == localCopyOfTouchBeginOrPanIncrement else { return }
self.currentTouchIsStillAndActive = false
self.updateBounceLockoutState()
}
updateBounceLockoutState()
return true
}
public func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
return true
}
}
extension PullToDismissTransition: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
switch transitionType {
case .slideStatic, .slideDynamic:
return Const.transitionDurationDragSlide
case .scale:
return Const.transitionDurationDragScale
}
}
private func setupTransitionViewsIfNecessary(
using transitionContext: UIViewControllerContextTransitioning,
in viewController: UIViewController
) {
if isDimmingEnabled && dimmingView == nil {
let dimmingView = UIView()
dimmingView.alpha = Const.dimmingPeakAlpha
dimmingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dimmingView.frame = transitionContext.containerView.bounds
let color: UIColor
switch transitionType {
case .slideStatic, .slideDynamic:
color = .black
case .scale:
color = .white
}
dimmingView.backgroundColor = color
self.dimmingView = dimmingView
transitionContext.containerView.insertSubview(dimmingView, belowSubview: viewController.view)
}
if transitionType != .slideDynamic && scalingView == nil,
let scalingView = viewController.view.resizableSnapshotView(
from: viewController.view.bounds,
afterScreenUpdates: true,
withCapInsets: .zero
) {
scalingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scalingView.frame = transitionContext.containerView.bounds
scalingView.transform = .identity
self.scalingView = scalingView
transitionContext.containerView.insertSubview(scalingView, aboveSubview: viewController.view)
viewController.view.isHidden = true
var shouldRoundCorners = false
switch transitionType {
case .slideStatic, .slideDynamic:
break
case .scale:
shouldRoundCorners = true
}
if #available(iOS 10.0, *) {
if shouldRoundCorners {
scalingView.layer.masksToBounds = true
UIViewPropertyAnimator(
duration: Const.scalingViewCornerRadiusToggleDuration,
curve: .easeIn
) {
scalingView.layer.cornerRadius = Const.scalingViewCornerRadius
}.startAnimation()
}
}
}
}
private func tearDownTransitionViewsAsNecessary(
using transitionContext: UIViewControllerContextTransitioning,
for viewController: UIViewController,
completionHandler: (() -> Void)? = nil
) {
if transitionContext.transitionWasCancelled, let scalingView = scalingView {
if #available(iOS 10.0, *) {
if scalingView.layer.cornerRadius > 0 {
viewController.view.layer.cornerRadius = scalingView.layer.cornerRadius
viewController.view.layer.masksToBounds = true
UIViewPropertyAnimator(
duration: Const.scalingViewCornerRadiusToggleDuration,
curve: .easeIn
) {
viewController.view.layer.cornerRadius = 0
}.startAnimation()
}
}
viewController.view.isHidden = false
scalingView.removeFromSuperview()
self.scalingView = nil
}
let completeBlock: (Bool) -> Void = { [weak self] finished -> Void in
if finished {
self?.dimmingView?.removeFromSuperview()
self?.dimmingView = nil
}
completionHandler?()
}
if dimmingView != nil {
var holdDimmingView = false
switch transitionType {
case .slideStatic, .slideDynamic:
holdDimmingView = false
case .scale:
holdDimmingView = !transitionContext.transitionWasCancelled
}
if holdDimmingView {
UIView.animate(
withDuration: Const.dimmingAlphaTransitionFinishDropDelay,
animations: { [weak self] in
self?.dimmingView?.alpha = transitionContext.transitionWasCancelled ? 1 : 0
},
completion: completeBlock
)
return
}
}
completeBlock(true)
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVc = transitionContext.viewController(
forKey: UITransitionContextViewControllerKey.from
) else { return }
setupTransitionViewsIfNecessary(using: transitionContext, in: fromVc)
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
delay: 0,
options: animationOptions,
animations: { [weak self] in
guard let strongSelf = self else { return }
switch strongSelf.transitionType {
case .slideStatic, .slideDynamic:
guard let slideView = (
strongSelf.transitionType == .slideDynamic
?
fromVc.view
:
strongSelf.scalingView
) else { break }
slideView.frame = slideView.frame.offsetBy(
dx: 0,
dy: slideView.window?.bounds.height ?? 0
)
strongSelf.dimmingView?.alpha = 0
case .scale:
guard let scalingView = strongSelf.scalingView else { break }
scalingView.alpha = 0
scalingView.frame = scalingView.frame.insetBy(
dx: scalingView.frame.width / Const.scalingPeakScaleDivider,
dy: scalingView.frame.height / Const.scalingPeakScaleDivider
)
}
},
completion: { [weak self] _ in
self?.tearDownTransitionViewsAsNecessary(
using: transitionContext,
for: fromVc,
completionHandler: {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
)
}
)
}
}