forked from 52inc/Pulley
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPulleyViewController.swift
614 lines (476 loc) · 23.5 KB
/
PulleyViewController.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//
// PulleyViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
// Copyright © 2016 52inc. All rights reserved.
//
import UIKit
/**
* The base delegate protocol for Pulley delegates.
*/
@objc public protocol PulleyDelegate: class {
optional func drawerPositionDidChange(drawer: PulleyViewController)
optional func makeUIAdjustmentsForFullscreen(progress: CGFloat)
optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat)
}
/**
* View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions.
*/
@objc public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate {
func collapsedDrawerHeight() -> CGFloat
func partialRevealDrawerHeight() -> CGFloat
}
/**
* View controllers that are the main content can implement this to receive changes in state.
*/
@objc public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate {
// Not currently used for anything, but it's here for parity with the hopes that it'll one day be used.
}
/**
Represents a Pulley drawer position.
- Collapsed: When the drawer is in its smallest form, at the bottom of the screen.
- PartiallyRevealed: When the drawer is partially revealed.
- Open: When the drawer is fully open.
*/
public enum PulleyPosition {
case Collapsed
case PartiallyRevealed
case Open
}
private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0
private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0
public class PulleyViewController: UIViewController, UIScrollViewDelegate, PulleyPassthroughScrollViewDelegate {
// Interface Builder
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet var primaryContentContainerView: UIView!
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet var drawerContentContainerView: UIView!
// Internal
private let primaryContentContainer: UIView = UIView()
private let drawerContentContainer: UIView = UIView()
private let drawerShadowView: UIView = UIView()
private let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView()
private let backgroundDimmingView: UIView = UIView()
private var dimmingViewTapRecognizer: UITapGestureRecognizer?
/// The current content view controller (shown behind the drawer).
private(set) var primaryContentViewController: UIViewController! {
willSet {
guard let controller = primaryContentViewController else {
return;
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
}
didSet {
guard let controller = primaryContentViewController else {
return;
}
controller.view.translatesAutoresizingMaskIntoConstraints = true
self.primaryContentContainer.addSubview(controller.view)
self.addChildViewController(controller)
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The current drawer view controller (shown in the drawer).
private(set) var drawerContentViewController: UIViewController! {
willSet {
guard let controller = drawerContentViewController else {
return;
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
}
didSet {
guard let controller = drawerContentViewController else {
return;
}
controller.view.translatesAutoresizingMaskIntoConstraints = true
self.drawerContentContainer.addSubview(controller.view)
self.addChildViewController(controller)
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed.
public weak var delegate: PulleyDelegate?
/// The current position of the drawer.
public private(set) var drawerPosition: PulleyPosition = .Collapsed
/// The inset from the top of the view controller when fully open.
public var topInset: CGFloat = 50.0 {
didSet {
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The corner radius for the drawer.
public var drawerCornerRadius: CGFloat = 13.0 {
didSet {
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The opacity of the drawer shadow.
public var shadowOpacity: Float = 0.1 {
didSet {
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The radius of the drawer shadow.
public var shadowRadius: CGFloat = 3.0 {
didSet {
if self.isViewLoaded()
{
self.view.setNeedsLayout()
}
}
}
/// The opaque color of the background dimming view.
public var backgroundDimmingColor: UIColor = UIColor.blackColor() {
didSet {
if self.isViewLoaded()
{
backgroundDimmingView.backgroundColor = backgroundDimmingColor
}
}
}
/// The maximum amount of opacity when dimming.
public var backgroundDimmingOpacity: CGFloat = 0.5 {
didSet {
if self.isViewLoaded()
{
self.scrollViewDidScroll(drawerScrollView)
}
}
}
/**
Initialize the drawer controller programmtically.
- parameter contentViewController: The content view controller. This view controller is shown behind the drawer.
- parameter drawerViewController: The view controller to display inside the drawer.
- note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account.
- returns: A newly created Pulley drawer.
*/
required public init(contentViewController: UIViewController, drawerViewController: UIViewController) {
super.init(nibName: nil, bundle: nil)
({
self.primaryContentViewController = contentViewController
self.drawerContentViewController = drawerViewController
})()
}
/**
Initialize the drawer controller from Interface Builder.
- note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container.
- parameter aDecoder: The NSCoder to decode from.
- returns: A newly created Pulley drawer.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func loadView() {
super.loadView()
// IB Support
if primaryContentContainerView != nil
{
primaryContentContainerView.removeFromSuperview()
}
if drawerContentContainerView != nil
{
drawerContentContainerView.removeFromSuperview()
}
// Setup
primaryContentContainer.backgroundColor = UIColor.whiteColor()
drawerScrollView.bounces = false
drawerScrollView.delegate = self
drawerScrollView.clipsToBounds = false
drawerScrollView.showsVerticalScrollIndicator = false
drawerScrollView.showsHorizontalScrollIndicator = false
drawerScrollView.delaysContentTouches = true
drawerScrollView.canCancelContentTouches = true
drawerScrollView.backgroundColor = UIColor.clearColor()
drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast
drawerScrollView.touchDelegate = self
drawerShadowView.layer.shadowOpacity = shadowOpacity
drawerShadowView.layer.shadowRadius = shadowRadius
drawerShadowView.backgroundColor = UIColor.clearColor()
drawerContentContainer.backgroundColor = UIColor.clearColor()
backgroundDimmingView.backgroundColor = backgroundDimmingColor
backgroundDimmingView.userInteractionEnabled = false
backgroundDimmingView.alpha = 0.0
dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizer(_:)))
backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!)
drawerScrollView.addSubview(drawerShadowView)
drawerScrollView.addSubview(drawerContentContainer)
primaryContentContainer.backgroundColor = UIColor.whiteColor()
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(primaryContentContainer)
self.view.addSubview(backgroundDimmingView)
self.view.addSubview(drawerScrollView)
}
public override func viewDidLoad() {
super.viewDidLoad()
// IB Support
if primaryContentViewController == nil || drawerContentViewController == nil
{
assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.")
// Locate main content VC
for child in self.childViewControllers
{
if child.view == primaryContentContainerView.subviews.first
{
primaryContentViewController = child
}
if child.view == drawerContentContainerView.subviews.first
{
drawerContentViewController = child
}
}
assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.")
}
scrollViewDidScroll(drawerScrollView)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout main content
primaryContentContainer.frame = self.view.bounds
backgroundDimmingView.frame = self.view.bounds
// Layout scrollview
drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset)
// Layout container
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].minElement() ?? 0
let bounceOverflowMargin: CGFloat = 20.0
drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin)
drawerShadowView.frame = drawerContentContainer.frame
drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height)
// Update rounding mask and shadows
let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: [.TopLeft, .TopRight], cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).CGPath
let cardMaskLayer = CAShapeLayer()
cardMaskLayer.path = borderPath
cardMaskLayer.fillColor = UIColor.whiteColor().CGColor
cardMaskLayer.backgroundColor = UIColor.clearColor().CGColor
drawerContentContainer.layer.mask = cardMaskLayer
drawerShadowView.layer.shadowPath = borderPath
// Make VC views match frames
primaryContentViewController.view.frame = primaryContentContainer.bounds
drawerContentViewController.view.frame = CGRect(x: drawerContentContainer.bounds.minX, y: drawerContentContainer.bounds.minY, width: drawerContentContainer.bounds.width, height: drawerContentContainer.bounds.height)
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Configuration Updates
/**
Set the drawer position, with an option to animate.
- parameter position: The position to set the drawer to.
- parameter animated: Whether or not to animate the change. (Default: true)
*/
public func setDrawerPosition(position: PulleyPosition, animated: Bool = true)
{
drawerPosition = position
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let stopToMoveTo: CGFloat
switch drawerPosition {
case .Collapsed:
stopToMoveTo = collapsedHeight
case .PartiallyRevealed:
stopToMoveTo = partialRevealHeight
case .Open:
stopToMoveTo = (self.view.bounds.size.height - topInset)
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.minElement() ?? 0
if animated
{
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .CurveEaseInOut, animations: { [weak self] () -> Void in
self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
if let drawer = self
{
drawer.delegate?.drawerPositionDidChange?(drawer)
(drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer)
(drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer)
drawer.view.layoutIfNeeded()
}
}, completion: nil)
}
else
{
drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
delegate?.drawerPositionDidChange?(self)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(self)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(self)
}
}
/**
Change the current primary content view controller (The one behind the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change. Defaults to true.
*/
public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true)
{
if animated
{
UIView.transitionWithView(primaryContentContainer, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { [weak self] () -> Void in
self?.primaryContentViewController = controller
}, completion: nil)
}
else
{
primaryContentViewController = controller
}
}
/**
Change the current drawer content view controller (The one inside the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change.
*/
public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true)
{
if animated
{
UIView.transitionWithView(drawerContentContainer, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { [weak self] () -> Void in
self?.drawerContentViewController = controller
self?.setDrawerPosition(self?.drawerPosition ?? .Collapsed, animated: false)
}, completion: nil)
}
else
{
drawerContentViewController = controller
setDrawerPosition(drawerPosition, animated: false)
}
}
// MARK: Actions
func dimmingViewTapRecognizer(gestureRecognizer: UITapGestureRecognizer)
{
if gestureRecognizer == dimmingViewTapRecognizer
{
if gestureRecognizer.state == .Recognized
{
self.setDrawerPosition(.Collapsed, animated: true)
}
}
}
// MARK: UIScrollViewDelegate
private var lastDragTargetContentOffset: CGPoint = CGPoint.zero
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == drawerScrollView
{
// Find the closest anchor point and snap there.
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.minElement() ?? 0
let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y
var currentClosestStop = lowestStop
for currentStop in drawerStops
{
if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView)
{
currentClosestStop = currentStop
}
}
if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= FLT_EPSILON
{
setDrawerPosition(.Open, animated: true)
} else if abs(Float(currentClosestStop - collapsedHeight)) <= FLT_EPSILON
{
setDrawerPosition(.Collapsed, animated: true)
} else {
setDrawerPosition(.PartiallyRevealed, animated: true)
}
}
}
public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if scrollView == drawerScrollView
{
lastDragTargetContentOffset = targetContentOffset.memory
// Halt intertia
targetContentOffset.memory = scrollView.contentOffset
}
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == drawerScrollView
{
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight()
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight()
}
let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight]
let lowestStop = drawerStops.minElement() ?? 0
if scrollView.contentOffset.y > partialRevealHeight - lowestStop
{
// Calculate percentage between partial and full reveal
let fullRevealHeight = (self.view.bounds.size.height - topInset)
let progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight))
delegate?.makeUIAdjustmentsForFullscreen?(progress)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress)
backgroundDimmingView.alpha = progress * backgroundDimmingOpacity
backgroundDimmingView.userInteractionEnabled = true
}
else
{
if backgroundDimmingView.alpha >= 0.001
{
backgroundDimmingView.alpha = 0.0
delegate?.makeUIAdjustmentsForFullscreen?(0.0)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(0.0)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(0.0)
backgroundDimmingView.userInteractionEnabled = false
}
}
delegate?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(self, distance: scrollView.contentOffset.y + lowestStop)
}
}
// MARK: Touch Passthrough ScrollView Delegate
func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool
{
let contentDrawerLocation = drawerContentContainer.frame.origin.y
if point.y < contentDrawerLocation
{
return true
}
return false
}
func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView
{
if drawerPosition == .Open
{
return backgroundDimmingView
}
return primaryContentContainer
}
}