forked from nakajijapan/PhotoSlider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewController.swift
680 lines (538 loc) · 23.3 KB
/
ViewController.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//
// ViewController.swift
//
// Created by nakajijapan on 3/28/15.
// Copyright (c) 2015 net.nakajijapan. All rights reserved.
//
import UIKit
@objc public protocol PhotoSliderDelegate {
@objc optional func photoSliderControllerWillDismiss(_ viewController: PhotoSlider.ViewController)
@objc optional func photoSliderControllerDidDismiss(_ viewController: PhotoSlider.ViewController)
}
enum PhotoSliderControllerScrollMode: UInt {
case None = 0, Vertical, Horizontal, Rotating
}
enum PhotoSliderControllerUsingImageType: UInt {
case None = 0, URL, Image, Photo
}
public class ViewController: UIViewController {
lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: CGRect(
x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.delegate = self
scrollView.clipsToBounds = false
scrollView.alwaysBounceHorizontal = true
scrollView.alwaysBounceVertical = true
scrollView.isScrollEnabled = true
scrollView.accessibilityLabel = "PhotoSliderScrollView"
scrollView.contentSize = CGSize(
width: self.view.bounds.width * CGFloat(self.imageResources()!.count),
height: self.view.bounds.height * 3.0
)
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
return scrollView
}()
var imageURLs: [URL]?
var images: [UIImage]?
var photos: [PhotoSlider.Photo]?
var usingImageType: PhotoSliderControllerUsingImageType = .None
lazy var backgroundView: UIView = {
let backgroundView = UIView(frame: self.view.bounds)
backgroundView.backgroundColor = self.backgroundViewColor
return backgroundView
}()
lazy var captionBackgroundView: UIView = {
var captionBackgroundView = UIView()
if let captionHeight = captionHeight {
var y = view.bounds.height - captionHeight - 32.0
var height = captionHeight + 32.0
if #available(iOS 11.0, *), let window = UIApplication.shared.keyWindow {
let bottomSafeInsetSpacing = window.safeAreaInsets.bottom
height += bottomSafeInsetSpacing
y -= bottomSafeInsetSpacing
}
let frame = CGRect(x: 0, y: y, width: view.bounds.width, height: height)
captionBackgroundView = UIView(frame: frame)
}
captionBackgroundView.backgroundColor = captionBackgroundViewColor
return captionBackgroundView
}()
lazy var effectView: UIVisualEffectView = {
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
effectView.frame = self.view.bounds
return effectView
}()
lazy var closeButton: UIButton = {
let closeButton = UIButton(frame: CGRect.zero)
let imagePath = self.resourceBundle().path(forResource: "PhotoSliderClose", ofType: "png")
closeButton.setImage(UIImage(contentsOfFile: imagePath!), for: .normal)
closeButton.addTarget(self, action: #selector(closeButtonDidTap(_:)), for: .touchUpInside)
closeButton.imageView?.contentMode = UIViewContentMode.center
closeButton.layer.shadowColor = UIColor.black.cgColor
closeButton.layer.shadowOffset = CGSize(width: 1, height: 1)
closeButton.layer.shadowRadius = 3
closeButton.layer.shadowOpacity = 1
return closeButton
}()
var scrollMode: PhotoSliderControllerScrollMode = .None
var scrollInitalized = false
var closeAnimating = false
var imageViews: [PhotoSlider.ImageView] = []
var previousPage = 0
lazy var captionLabel: UILabel = {
let label = UILabel(frame: CGRect.zero)
label.textColor = self.captionTextColor
label.numberOfLines = self.captionNumberOfLines
return label
}()
// For ScrollViewDelegate
var scrollPreviewPoint = CGPoint.zero
public weak var delegate: PhotoSliderDelegate?
public var visiblePageControl = true
public var visibleCloseButton = true
public var currentPage = 0
public var captionNumberOfLines = 3
lazy public var pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.frame = .zero
pageControl.numberOfPages = self.imageResources()!.count
pageControl.isUserInteractionEnabled = false
return pageControl
}()
public var captionHeight: CGFloat?
public var captionBackgroundViewColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4)
public var backgroundViewColor = UIColor.black
public var captionTextColor = UIColor.white
public var imageLoader: PhotoSlider.ImageLoader?
public init(imageURLs: [URL]) {
super.init(nibName: nil, bundle: nil)
self.imageURLs = imageURLs
usingImageType = .URL
}
public init(images: [UIImage]) {
super.init(nibName: nil, bundle: nil)
self.images = images
usingImageType = .Image
}
public init(photos: [PhotoSlider.Photo]) {
super.init(nibName: nil, bundle: nil)
self.photos = photos
usingImageType = .Photo
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var statusBarHidden = false
override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
override public var prefersStatusBarHidden: Bool {
return statusBarHidden
}
public override func viewDidLoad() {
super.viewDidLoad()
view.frame = UIScreen.main.bounds
view.backgroundColor = UIColor.clear
view.addSubview(effectView)
effectView.contentView.addSubview(backgroundView)
// scrollview setting for Item
view.addSubview(scrollView)
layoutScrollView()
let width = view.bounds.width
let height = view.bounds.height
var frame = view.bounds
frame.origin.y = height
if imageLoader == nil {
imageLoader = PhotoSlider.KingfisherImageLoader()
}
for imageResource in imageResources()! {
let imageView: PhotoSlider.ImageView = PhotoSlider.ImageView(frame: frame)
imageView.delegate = self
imageView.imageLoader = imageLoader
scrollView.addSubview(imageView)
if imageResource is URL {
imageView.loadImage(imageURL: imageResource as! URL)
} else if imageResource is UIImage {
imageView.setImage(image: imageResource as! UIImage)
} else {
let photo = imageResource as! PhotoSlider.Photo
if photo.imageURL != nil {
imageView.loadImage(imageURL: photo.imageURL!)
} else {
imageView.setImage(image: photo.image!)
}
}
frame.origin.x += width
imageViews.append(imageView)
}
// Close Button
if visibleCloseButton {
view.addSubview(closeButton)
layoutCloseButton()
}
// Caption Background
view.addSubview(captionBackgroundView)
// Page Control
if visiblePageControl {
captionBackgroundView.addSubview(pageControl)
layoutPageControl()
}
// Caption
captionBackgroundView.addSubview(captionLabel)
layoutCaptionLabel()
updateCaption()
if captionHeight == nil {
layoutCaptionBackgroundView()
}
if width > height {
statusBarHidden = true
}
setNeedsStatusBarAppearanceUpdate()
}
@objc func closeButtonDidTap(_ sender: UIButton) {
delegate?.photoSliderControllerWillDismiss?(self)
dissmissViewControllerAnimated(animated: true)
}
override public func viewWillAppear(_ animated: Bool) {
scrollView.contentOffset = CGPoint(
x: scrollView.bounds.width * CGFloat(currentPage),
y: scrollView.bounds.height
)
scrollInitalized = true
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
statusBarHidden = true
UIView.animate(withDuration: 0.5) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
}
// MARK: - Setup Layout
fileprivate extension ViewController {
func layoutScrollView() {
scrollView.translatesAutoresizingMaskIntoConstraints = false
[
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0),
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0),
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0),
].forEach { $0.isActive = true }
}
func layoutCloseButton() {
closeButton.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
[
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0),
closeButton.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0.0),
closeButton.heightAnchor.constraint(equalToConstant: 52.0),
closeButton.widthAnchor.constraint(equalToConstant: 52.0),
].forEach { $0.isActive = true }
} else {
[
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0),
closeButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0),
closeButton.heightAnchor.constraint(equalToConstant: 52.0),
closeButton.widthAnchor.constraint(equalToConstant: 52.0),
].forEach { $0.isActive = true }
}
}
func layoutPageControl() {
pageControl.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
[
pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0.0),
pageControl.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
pageControl.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: 0.0),
pageControl.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0.0),
].forEach { $0.isActive = true }
} else {
[
pageControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0),
pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
pageControl.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0.0),
pageControl.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0.0),
].forEach { $0.isActive = true }
}
}
func layoutCaptionLabel() {
captionLabel.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
[
captionLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -32.0),
captionLabel.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -16.0),
captionLabel.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 16.0),
].forEach { $0.isActive = true }
} else {
[
captionLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32.0),
captionLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -16.0),
captionLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 16.0),
].forEach { $0.isActive = true }
}
if let captionHeight = captionHeight {
captionLabel.heightAnchor.constraint(equalToConstant: captionHeight).isActive = true
}
}
func layoutCaptionBackgroundView() {
captionBackgroundView.translatesAutoresizingMaskIntoConstraints = false
[captionBackgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
captionBackgroundView.rightAnchor.constraint(equalTo: view.rightAnchor),
captionBackgroundView.leftAnchor.constraint(equalTo: view.leftAnchor),
captionBackgroundView.topAnchor.constraint(equalTo: captionLabel.topAnchor, constant: -16.0)
].forEach { $0.isActive = true }
}
}
// MARK: - UIScrollViewDelegate
extension ViewController: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
previousPage = currentPage
scrollPreviewPoint = scrollView.contentOffset
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !scrollInitalized {
generateCurrentPage()
return
}
let imageView = imageViews[currentPage]
if imageView.scrollView.zoomScale > 1.0 {
generateCurrentPage()
scrollView.isScrollEnabled = false
return
}
if scrollMode == .Rotating {
return
}
let offsetX = fabs(scrollView.contentOffset.x - scrollPreviewPoint.x)
let offsetY = fabs(scrollView.contentOffset.y - scrollPreviewPoint.y)
if scrollMode == .None {
if offsetY > offsetX {
scrollMode = .Vertical
} else {
scrollMode = .Horizontal
}
}
if scrollMode == .Vertical {
let offsetHeight = fabs(scrollView.frame.size.height - scrollView.contentOffset.y)
let alpha = 1.0 - ( fabs(offsetHeight) / (scrollView.frame.size.height / 2.0) )
backgroundView.alpha = alpha
var contentOffset = scrollView.contentOffset
contentOffset.x = scrollPreviewPoint.x
scrollView.contentOffset = contentOffset
let screenHeight = UIScreen.main.bounds.size.height
if scrollView.contentOffset.y > screenHeight * 1.4 {
closePhotoSlider(movingUp: true)
} else if scrollView.contentOffset.y < screenHeight * 0.6 {
closePhotoSlider(movingUp: false)
}
} else if scrollMode == .Horizontal {
var contentOffset = scrollView.contentOffset
contentOffset.y = scrollPreviewPoint.y
scrollView.contentOffset = contentOffset
}
// Update current page index.
generateCurrentPage()
}
fileprivate func generateCurrentPage() {
var page = Int(round(scrollView.contentOffset.x / scrollView.frame.size.width))
if page < 0 {
page = 0
} else if page >= imageResources()!.count {
page = imageResources()!.count - 1
}
currentPage = page
if visiblePageControl {
pageControl.currentPage = currentPage
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollMode == .Vertical {
let velocity = scrollView.panGestureRecognizer.velocity(in: scrollView)
if velocity.y < -500 {
scrollView.frame = scrollView.frame
closePhotoSlider(movingUp: true)
} else if velocity.y > 500 {
scrollView.frame = scrollView.frame
closePhotoSlider(movingUp: false)
}
}
}
fileprivate func closePhotoSlider(movingUp: Bool) {
if closeAnimating == true {
return
}
closeAnimating = true
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
var movedHeight = CGFloat(0)
delegate?.photoSliderControllerWillDismiss?(self)
if movingUp {
movedHeight = -screenHeight
} else {
movedHeight = screenHeight
}
UIView.animate(
withDuration: 0.4,
delay: 0,
options: .curveEaseOut,
animations: { () -> Void in
self.scrollView.frame = CGRect(x: 0, y: movedHeight, width: screenWidth, height: screenHeight)
self.backgroundView.alpha = 0.0
self.closeButton.alpha = 0.0
self.captionLabel.alpha = 0.0
self.view.alpha = 0.0
},
completion: { _ -> Void in
self.dissmissViewControllerAnimated(animated: false)
self.closeAnimating = false
}
)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if previousPage != currentPage {
// If page index has changed - reset zoom scale for previous image.
let imageView = imageViews[previousPage]
imageView.scrollView.zoomScale = imageView.scrollView.minimumZoomScale
// Show Caption Label
updateCaption()
}
scrollMode = .None
}
}
// MARK: - PhotoSliderImageViewDelegate
extension ViewController: PhotoSliderImageViewDelegate {
func photoSliderImageViewDidEndZooming(_ viewController: PhotoSlider.ImageView, atScale scale: CGFloat) {
if scale <= 1.0 {
scrollView.isScrollEnabled = true
UIView.animate(withDuration: 0.05, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.closeButton.alpha = 1.0
self.captionLabel.alpha = 1.0
if let captionText = self.captionLabel.text, !captionText.isEmpty {
self.captionBackgroundView.backgroundColor = self.captionBackgroundViewColor
}
if self.visiblePageControl {
self.pageControl.alpha = 1.0
}
}, completion: nil)
} else {
scrollView.isScrollEnabled = false
UIView.animate(withDuration: 0.05, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.closeButton.alpha = 0.0
self.captionLabel.alpha = 0.0
self.captionBackgroundView.backgroundColor = .clear
if self.visiblePageControl {
self.pageControl.alpha = 0.0
}
}, completion: nil)
}
}
func dissmissViewControllerAnimated(animated: Bool) {
dismiss(animated: animated, completion: { () -> Void in
self.delegate?.photoSliderControllerDidDismiss?(self)
})
}
fileprivate func resourceBundle() -> Bundle {
let bundlePath = Bundle.main.path(
forResource: "PhotoSlider",
ofType: "bundle",
inDirectory: "Frameworks/PhotoSlider.framework"
)
if bundlePath != nil {
return Bundle(path: bundlePath!)!
}
return Bundle(for: type(of: self))
}
}
// MARK: - UITraitEnvironmenat
extension ViewController {
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
scrollMode = .Rotating
let contentViewBounds = view.bounds
let height = contentViewBounds.height
// Background View
backgroundView.frame = contentViewBounds
// Scroll View
scrollView.contentSize = CGSize(
width: contentViewBounds.width * CGFloat(imageResources()!.count),
height: contentViewBounds.height * 3.0
)
scrollView.frame = contentViewBounds
// ImageViews
var frame = CGRect(x: 0.0, y: contentViewBounds.height, width: contentViewBounds.width, height: contentViewBounds.height)
for i in 0..<scrollView.subviews.count {
let imageView = scrollView.subviews[i] as! PhotoSlider.ImageView
imageView.frame = frame
frame.origin.x += contentViewBounds.size.width
imageView.scrollView.frame = contentViewBounds
imageView.layoutImageView()
}
scrollView.contentOffset = CGPoint(x: CGFloat(currentPage) * contentViewBounds.width, y: height)
scrollMode = .None
}
}
// MARK: - ZoomingAnimationControllerTransitioning
extension ViewController: ZoomingAnimationControllerTransitioning {
public func transitionSourceImageView() -> UIImageView {
let zoomingImageView = imageViews[currentPage]
zoomingImageView.imageView.clipsToBounds = true
zoomingImageView.imageView.contentMode = UIViewContentMode.scaleAspectFill
return zoomingImageView.imageView
}
public func transitionDestinationImageView(sourceImageView: UIImageView) {
guard let sourceImage = sourceImageView.image else { return }
var height: CGFloat = 0.0
var width: CGFloat = 0.0
if view.bounds.width < view.bounds.height {
height = (view.frame.width * sourceImage.size.height) / sourceImage.size.width
width = view.frame.width
} else {
height = view.frame.height
width = (view.frame.height * sourceImage.size.width) / sourceImage.size.height
}
sourceImageView.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
sourceImageView.center = CGPoint(
x: view.frame.width * 0.5,
y: view.frame.height * 0.5
)
}
// Private Method
fileprivate func imageResources() -> [AnyObject]? {
if usingImageType == .URL {
return imageURLs as [AnyObject]?
} else if usingImageType == .Image {
return images
} else if usingImageType == .Photo {
return photos
}
return nil
}
fileprivate func updateCaption() {
if usingImageType == .Photo {
if imageResources()!.count > 0 {
let photo = photos![currentPage] as Photo
UIView.animate(
withDuration: 0.1,
delay: 0.0,
options: .curveLinear,
animations: { () -> Void in
self.captionLabel.alpha = 0.0
self.captionBackgroundView.backgroundColor = .clear
}, completion: { _ -> Void in
self.captionLabel.text = photo.caption
UIView.animate(withDuration: 0.1, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
self.captionLabel.alpha = 1.0
if let captionText = self.captionLabel.text, !captionText.isEmpty {
self.captionBackgroundView.backgroundColor = self.captionBackgroundViewColor
}
}, completion: nil)
})
}
}
}
}