-
Notifications
You must be signed in to change notification settings - Fork 44
/
AukDistrib.swift
1766 lines (1263 loc) · 52.2 KB
/
AukDistrib.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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// An image slideshow for iOS written in Swift.
//
// https://github.com/evgenyneu/Auk
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// AukPageVisibility.swift
//
// ----------------------------
import UIKit
/**
Helper functions that tell if the scroll view page is currently visible to the user.
*/
struct AukPageVisibility {
/**
Check if the given page is currently visible to user.
- parameter scrollView: Scroll view containing the page.
- parameter page: A scroll view page which visibility will be checked.
- returns: True if the page is visible to the user.
*/
static func isVisible(_ scrollView: UIScrollView, page: AukPage) -> Bool {
return scrollView.bounds.intersects(page.frame)
}
/**
Tells if the page is way out of sight. This is done to prevent cancelling download of the image for the page that is not very far out of sight.
- parameter scrollView: Scroll view containing the page.
- parameter page: A scroll view page which visibility will be checked.
- returns: True if the page is visible to the user.
*/
static func isFarOutOfSight(_ scrollView: UIScrollView, page: AukPage) -> Bool {
let parentRectWithIncreasedHorizontalBounds = scrollView.bounds.insetBy(dx: -50, dy: 0)
return !parentRectWithIncreasedHorizontalBounds.intersects(page.frame)
}
/**
Go through all the scroll view pages and tell them if they are visible or out of sight.
The pages, in turn, if they are visible start the download of the image
or cancel the download if they are out of sight.
- parameter scrollView: Scroll view with the pages.
*/
static func tellPagesAboutTheirVisibility(_ scrollView: UIScrollView,
settings: AukSettings,
currentPageIndex: Int) {
let pages = AukScrollViewContent.aukPages(scrollView)
for (index, page) in pages.enumerated() {
if isVisible(scrollView, page: page) {
page.visibleNow(settings)
} else {
if abs(index - currentPageIndex) <= settings.preloadRemoteImagesAround {
// Preload images for the pages around the current page
page.visibleNow(settings)
} else {
/*
The image is not visible to user and is not preloaded - cancel its download.
Now, this is a bit nuanced so let me explain. When we scroll into a new page we sometimes see a little bit of the next page. The scroll view animation overshoots a little bit to show the next page and then slides back to the current page. This is probably done on purpose for more natural spring bouncing effect.
When the scroll view overshoots and shows the next page, we call `isVisible` on it and it starts downloading its image. But because scroll view bounces back in a moment the page becomes invisible again very soon. If we just call `outOfSightNow()` the next page download will be canceled even though it has just been started. That is probably not very efficient use of network, so we call `isFarOutOfSight` function to check if the next page is way out of sight (and not just a little bit). If the page is out of sight but just by a little margin we still let it download the image.
*/
if isFarOutOfSight(scrollView, page: page) {
page.outOfSightNow()
}
}
}
}
}
}
// ----------------------------
//
// AukPage.swift
//
// ----------------------------
import UIKit
/// The view for an individual page of the scroll view containing an image.
final class AukPage: UIView {
// Image view for showing a placeholder image while remote image is being downloaded.
// The view is only created when a placeholder image is specified in settings.
weak var placeholderImageView: UIImageView?
// Image view for showing local and remote images
weak var imageView: UIImageView?
// Contains a URL for the remote image, if any.
var remoteImage: AukRemoteImage?
/**
Shows an image.
- parameter image: The image to be shown
- parameter settings: Auk settings.
*/
func show(image: UIImage, settings: AukSettings) {
imageView = createAndLayoutImageView(settings)
imageView?.image = image
}
/**
Shows a remote image. The image download stars if/when the page becomes visible to the user.
- parameter url: The URL to the image to be displayed.
- parameter settings: Auk settings.
*/
func show(url: String, settings: AukSettings) {
if settings.placeholderImage != nil {
placeholderImageView = createAndLayoutImageView(settings)
}
imageView = createAndLayoutImageView(settings)
if let imageView = imageView {
remoteImage = AukRemoteImage()
remoteImage?.setup(url, imageView: imageView, placeholderImageView: placeholderImageView,
settings: settings)
}
}
/**
Called when the page is currently visible to user which triggers the image download. The function is called frequently each time scroll view's content offset is changed.
*/
func visibleNow(_ settings: AukSettings) {
remoteImage?.downloadImage(settings)
}
/**
Called when the page is currently not visible to user which cancels the image download. The method called frequently each time scroll view's content offset is changed and the page is out of sight.
*/
func outOfSightNow() {
remoteImage?.cancelDownload()
}
/// Removes image views.
func removeImageViews() {
placeholderImageView?.removeFromSuperview()
placeholderImageView = nil
imageView?.removeFromSuperview()
imageView = nil
}
/**
Prepares the page view for reuse. Clears current content from the page and stops download.
*/
func prepareForReuse() {
removeImageViews()
remoteImage?.cancelDownload()
remoteImage = nil
}
/**
Create and layout the remote image view.
- parameter settings: Auk settings.
*/
func createAndLayoutImageView(_ settings: AukSettings) -> UIImageView {
let newImageView = AukPage.createImageView(settings)
addSubview(newImageView)
AukPage.layoutImageView(newImageView, superview: self)
return newImageView
}
private static func createImageView(_ settings: AukSettings) -> UIImageView {
let newImageView = UIImageView()
newImageView.contentMode = settings.contentMode
return newImageView
}
/**
Creates Auto Layout constrains for the image view.
- parameter imageView: Image view that is used to create Auto Layout constraints.
*/
private static func layoutImageView(_ imageView: UIImageView, superview: UIView) {
imageView.translatesAutoresizingMaskIntoConstraints = false
iiAutolayoutConstraints.fillParent(imageView, parentView: superview, margin: 0, vertically: false)
iiAutolayoutConstraints.fillParent(imageView, parentView: superview, margin: 0, vertically: true)
}
func makeAccessible(_ accessibilityLabel: String?) {
isAccessibilityElement = true
accessibilityTraits = UIAccessibilityTraits.image
self.accessibilityLabel = accessibilityLabel
}
}
// ----------------------------
//
// Auk.swift
//
// ----------------------------
import UIKit
/**
Shows images in the scroll view with page indicator.
Auk extends UIScrollView class by creating the auk property that you can use for showing images.
Usage:
// Show remote image
scrollView.auk.show(url: "http://site.com/bird.jpg")
// Show local image
if let image = UIImage(named: "bird.jpg") {
scrollView.auk.show(image: image)
}
*/
public class Auk {
// ---------------------------------
//
// MARK: - Public interface
//
// ---------------------------------
/**
Settings that control appearance of the images and page indicator.
*/
public var settings = AukSettings()
/**
Shows a local image in the scroll view.
- parameter image: Image to be shown in the scroll view.
- parameter accessibilityLabel: Text describing the image that will be spoken in accessibility mode. For example: "Picture of a pony standing in a flower pot.".
*/
public func show(image: UIImage, accessibilityLabel: String? = nil) {
setup()
let page = createPage(accessibilityLabel)
page.show(image: image, settings: settings)
}
/**
Downloads a remote image and adds it to the scroll view. Use `Moa.settings.cache` property to configure image caching.
- parameter url: Url of the image to be shown.
- parameter accessibilityLabel: Text describing the image that will be spoken in accessibility mode. For example: "Picture of a pony standing in a flower pot.".
*/
public func show(url: String, accessibilityLabel: String? = nil) {
setup()
let page = createPage(accessibilityLabel)
page.show(url: url, settings: settings)
tellPagesAboutTheirVisibility()
}
/**
Replaces an image on a given page.
- parameter atIndex: the index of the image to change. Does nothing if the index is less than zero or greater than the largest index.
- parameter image: Image to be shown in the scroll view.
- parameter accessibilityLabel: Text describing the image that will be spoken in accessibility mode.
For example: "Picture of a pony standing in a flower pot.".
*/
public func updatePage(atIndex index: Int, image: UIImage, accessibilityLabel: String? = nil) {
guard let scrollView = scrollView,
let page = AukScrollViewContent.page(atIndex: index, scrollView: scrollView) else { return }
page.prepareForReuse()
page.accessibilityLabel = accessibilityLabel
page.show(image: image, settings: settings)
}
/**
Downloads an image and uses it to replace an image on a given page. The current image is replaced when the new image has finished downloading. Use `Moa.settings.cache` property to configure image caching.
- parameter atIndex: the index of the image to change. Does nothing if the index is less than zero or greater than the largest index.
- parameter url: Url of the image to be shown.
- parameter accessibilityLabel: Text describing the image that will be spoken in accessibility mode.
For example: "Picture of a pony standing in a flower pot.".
*/
public func updatePage(atIndex index: Int, url: String, accessibilityLabel: String? = nil) {
guard let scrollView = scrollView,
let page = AukScrollViewContent.page(atIndex: index, scrollView: scrollView) else { return }
var updateSettings = settings
// Use current image as a placeholder in order to avoid abrupt change
// while the new one is being downloaded
if let currentImage = page.imageView?.image {
updateSettings.placeholderImage = currentImage
}
page.prepareForReuse()
page.accessibilityLabel = accessibilityLabel
page.show(url: url, settings: updateSettings)
tellPagesAboutTheirVisibility()
}
/**
Changes the current page.
- parameter atIndex: Index of the page to show.
- parameter animated: The page change will be animated when `true`.
*/
public func scrollToPage(atIndex index: Int, animated: Bool) {
guard let scrollView = scrollView else { return }
AukScrollTo.scrollToPage(scrollView, atIndex: index, animated: animated,
numberOfPages: numberOfPages)
}
/**
Changes both the current page and the page width.
This function can be used for animating the scroll view content during orientation change. It is called in viewWillTransitionToSize and inside animateAlongsideTransition animation block.
override func viewWillTransitionToSize(size: CGSize,
withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let pageIndex = scrollView.auk.currentPageIndex else { return }
let newScrollViewWidth = size.width // Assuming scroll view occupies 100% of the screen width
coordinator.animate(alongsideTransition: { [weak self] _ in
self?.scrollView.auk.scrollToPage(atIndex: pageIndex, pageWidth: newScrollViewWidth, animated: false)
}, completion: nil)
}
More information: https://github.com/evgenyneu/Auk/wiki/Size-animation
- parameter atIndex: Index of the page that will be made a current page.
- parameter pageWidth: The new page width.
- parameter animated: The page change will be animated when `true`.
*/
public func scrollToPage(atIndex index: Int, pageWidth: CGFloat, animated: Bool) {
guard let scrollView = scrollView else { return }
AukScrollTo.scrollToPage(scrollView, atIndex: index, pageWidth: pageWidth,
animated: animated, numberOfPages: numberOfPages)
}
/**
Scrolls to the next page.
*/
public func scrollToNextPage() {
scrollToNextPage(cycle: true, animated: true)
}
/**
Scrolls to the next page.
- parameter cycle: If `true` it scrolls to the first page from the last one. If `false` the scrolling stops at the last page.
- parameter animated: The page change will be animated when `true`.
*/
public func scrollToNextPage(cycle: Bool, animated: Bool) {
guard let scrollView = scrollView, let currentPageIndex = currentPageIndex else { return }
AukScrollTo.scrollToNextPage(scrollView, cycle: cycle, animated: animated,
currentPageIndex: currentPageIndex, numberOfPages: numberOfPages)
}
/**
Scrolls to the previous page.
*/
public func scrollToPreviousPage() {
scrollToPreviousPage(cycle: true, animated: true)
}
/**
Scrolls to the previous page.
- parameter cycle: If true it scrolls to the last page from the first one. If false the scrolling stops at the first page.
- parameter animated: The page change will be animated when `true`.
*/
public func scrollToPreviousPage(cycle: Bool, animated: Bool) {
if let scrollView = scrollView, let currentPageIndex = currentPageIndex {
AukScrollTo.scrollToPreviousPage(scrollView, cycle: cycle, animated: animated,
currentPageIndex: currentPageIndex, numberOfPages: numberOfPages)
}
}
/**
Removes all images from the scroll view.
*/
public func removeAll() {
if let scrollView = scrollView {
let pages = AukScrollViewContent.aukPages(scrollView)
pages.forEach {
$0.removeFromSuperview()
}
}
updatePageIndicator()
}
/**
Removes page at current presented index from the scroll view.
Does nothing if there no current page.
- parameter animated: Boolean indicating if the layout update after the removal of the page should be animated, defaults to false.
- parameter completion: Closure executed when page has been removed and layout updated.
*/
public func removeCurrentPage(animated: Bool = false, completion: (() -> Void)? = nil) {
if let currentPageIndex = currentPageIndex {
removePage(atIndex: currentPageIndex, animated: animated, completion: completion)
}
}
/**
Removes page at the provided index from the scroll view.
Does nothing if the index does not represent an existing page.
- parameter index: The index of the page your want to remove from the scroll view.
- parameter animated: Optional Boolean indicating if the layout update after the removal of the page should be animated, defaults to false.
- parameter completion: Closure executed when page has been removed and layout updated.
*/
public func removePage(atIndex index: Int, animated: Bool = false, completion: (() -> Void)? = nil) {
guard let scrollView = scrollView,
let page = AukScrollViewContent.page(atIndex: index, scrollView: scrollView) else { return }
iiAnimator.fadeOut(view: page, animated: animated,
withDuration: settings.removePageFadeOutAnimationDurationSeconds,
completion: { [weak self] in
// Finish fading out. Now remove the page from the scroll view.
self?.removePage(page: page, animated: animated, completion: completion)
}
)
}
/// Returns the current number of pages.
public var numberOfPages: Int {
guard let scrollView = scrollView else { return 0 }
return AukScrollViewContent.aukPages(scrollView).count
}
/// Returns array of currently visible images. Placeholder images are not returned here.
public var images: [UIImage] {
guard let scrollView = scrollView else { return [] }
var images = [UIImage]()
for page in AukScrollViewContent.aukPages(scrollView) {
if let image = page.imageView?.image {
images.append(image)
}
}
return images
}
/**
Returns the current page index. If pages are being scrolled and there are two of them on screen the page index will indicate the page that occupies bigger portion of the screen at the moment. Returns nil if there are no pages. If scrolled way to the left or right beyond the pages it will return zero or the last index respectively.
*/
public var currentPageIndex: Int? {
guard let scrollView = scrollView else { return nil }
if numberOfPages == 0 { return nil }
let width = Double(scrollView.bounds.size.width)
let offset = Double(scrollView.contentOffset.x)
if width == 0 {
print("Auk WARNING: scroll view has zero width.")
return nil
}
var value = Int(round(offset / width))
// Page # 0 is the rightmost in the right-to-left language layout
if RightToLeft.isRightToLeft(scrollView) {
value = numberOfPages - value - 1
}
if value < 0 { value = 0 }
if value > numberOfPages - 1 { value = numberOfPages - 1 }
return value
}
/**
Starts auto scrolling of the pages with the given delay in seconds. Auto scrolling stops when the user starts scrolling manually.
- parameter delaySeconds: Amount of time in second each page is visible before scrolling to the next.
*/
public func startAutoScroll(delaySeconds: Double) {
startAutoScroll(delaySeconds: delaySeconds, forward: true,
cycle: true, animated: true)
}
/**
Starts auto scrolling of the pages with the given delay in seconds.
- parameter delaySeconds: Amount of time in second each page is visible before scrolling to the next.
- parameter forward: When true the scrolling is done from left to right direction.
- parameter cycle: If true it scrolls to the first page from the last one. If false the scrolling stops at the last page.
- parameter animated: The page change will be animated when `true`.
*/
public func startAutoScroll(delaySeconds: Double, forward: Bool,
cycle: Bool, animated: Bool) {
guard let scrollView = scrollView else { return }
autoscroll.startAutoScroll(scrollView, delaySeconds: delaySeconds,
forward: forward, cycle: cycle, animated: animated, auk: self)
}
/**
Stops auto scrolling of the pages.
*/
public func stopAutoScroll() {
autoscroll.stopAutoScroll()
}
// ---------------------------------
//
// MARK: - Internal functionality
//
// ---------------------------------
var scrollViewDelegate = AukScrollViewDelegate()
var pageIndicatorContainer: AukPageIndicatorContainer?
var autoscroll = AukAutoscroll()
private weak var scrollView: UIScrollView?
init(scrollView: UIScrollView) {
self.scrollView = scrollView
scrollViewDelegate.onScroll = { [weak self] in
self?.onScroll()
}
// We stop auto scrolling when the user starts scrolling manually
scrollViewDelegate.onScrollByUser = { [weak self] in
self?.stopAutoScroll()
}
scrollViewDelegate.delegate = scrollView.delegate
scrollView.delegate = scrollViewDelegate
}
func setup() {
createPageIndicator()
scrollView?.showsHorizontalScrollIndicator = settings.showsHorizontalScrollIndicator
scrollView?.isPagingEnabled = settings.pagingEnabled
}
/// Create a page, add it to the scroll view content and layout.
private func createPage(_ accessibilityLabel: String? = nil) -> AukPage {
let page = AukPage()
page.clipsToBounds = true
page.makeAccessible(accessibilityLabel)
guard let scrollView = scrollView else { return page }
// Pages are added to the left of the current page
// in the right-to-left language layout.
// So we need to increase content offset to keep the current page visible.
if RightToLeft.isRightToLeft(scrollView) && numberOfPages > 0 {
scrollView.contentOffset.x += scrollView.bounds.size.width
}
scrollView.addSubview(page)
AukScrollViewContent.layout(scrollView)
updatePageIndicator()
return page
}
func onScroll() {
guard let currentPageIndex = currentPageIndex else { return }
tellPagesAboutTheirVisibility()
pageIndicatorContainer?.updateCurrentPage(currentPageIndex)
}
func createPageIndicator() {
if !settings.pageControl.visible { return }
if pageIndicatorContainer != nil { return } // Already created a page indicator container
guard let scrollView = scrollView, let superview = scrollView.superview else { return }
let container = AukPageIndicatorContainer()
container.didTapPageControlCallback = didTapPageControl
superview.insertSubview(container, aboveSubview: scrollView)
pageIndicatorContainer = container
container.setup(settings, scrollView: scrollView)
}
/// Show the number of pages and indicate the current page on the page indicator.
func updatePageIndicator() {
pageIndicatorContainer?.updateNumberOfPages(numberOfPages)
guard let currentPageIndex = currentPageIndex else { return }
pageIndicatorContainer?.updateCurrentPage(currentPageIndex)
}
private func didTapPageControl(atIndex index: Int) {
scrollToPage(atIndex: index, animated: true)
}
/// Removes the page form the scroll view.
func removePage(page: AukPage, animated: Bool, completion: (() -> Void)? = nil) {
guard let scrollView = scrollView else { return }
page.remoteImage?.cancelDownload()
page.removeFromSuperview()
AukScrollViewContent.layout(scrollView, animated: animated,
animationDurationInSeconds: settings.removePageLayoutAnimationDurationSeconds,
completion: { [weak self] in
// Finished removing the page.
//Update the page indicator.
self?.updatePageIndicator()
// Tell pages if they are visible.
// This will start the download for the page that slided into the view in place of the removed page.
self?.tellPagesAboutTheirVisibility()
completion?()
}
)
}
/**
Go through all the scroll view pages and tell them if they are visible or out of sight.
The pages, in turn, if they are visible start the download of the image
or cancel the download if they are out of sight.
*/
func tellPagesAboutTheirVisibility() {
guard let scrollView = scrollView, let currentPageIndex = currentPageIndex else { return }
AukPageVisibility.tellPagesAboutTheirVisibility(scrollView, settings: settings,
currentPageIndex: currentPageIndex)
}
}
// ----------------------------
//
// AukSettings.swift
//
// ----------------------------
import UIKit
/**
Appearance and behavior of the scroll view.
*/
public struct AukSettings {
/// Determines the stretching and scaling of the image when its proportion are not the same as its container.
public var contentMode = UIView.ContentMode.scaleAspectFit
/// Image to be displayed when remote image download fails.
public var errorImage: UIImage?
/// Settings for styling the scroll view page indicator.
public var pageControl = PageControlSettings()
/// Enable paging for the scroll view. When true the view automatically scrolls to show the whole image.
public var pagingEnabled = true
/// Image to be displayed while the remote image is being downloaded.
public var placeholderImage: UIImage?
/**
The number of remote images to preload around the current page. For example, if preloadRemoteImagesAround = 2 and we are viewing the first page it will preload images on the second and third pages. If we are viewing 5th page then it will preload images on pages 3, 4, 6 and 7 (unless they are already loaded). The default value is 0, i.e. it only loads the image for the currently visible pages.
*/
public var preloadRemoteImagesAround = 0
/// The duration of the animation that is used to show the remote images.
public var remoteImageAnimationIntervalSeconds: Double = 0.5
// Duration of the fade out animation when the page is removed.
public var removePageFadeOutAnimationDurationSeconds: Double = 0.2
// Duration of the layout animation when the page is removed.
public var removePageLayoutAnimationDurationSeconds: Double = 0.3
/// Show horizontal scroll indicator.
public var showsHorizontalScrollIndicator = false
}
/**
Settings for page indicator.
*/
public struct PageControlSettings {
/// Background color of the page control container view.
public var backgroundColor = UIColor(red: 128/256, green: 128/256, blue: 128/256, alpha: 0.4)
/// Corner radius of page control container view.
public var cornerRadius: Double = 13
/// Color of the dot representing for the current page.
public var currentPageIndicatorTintColor: UIColor? = nil
/// Padding between page indicator and its container
public var innerPadding = CGSize(width: 10, height: -5)
/// Distance between the bottom of the page control view and the bottom of the scroll view.
public var marginToScrollViewBottom: Double = 8
/// Color of the page indicator dot.
public var pageIndicatorTintColor: UIColor? = nil
/// When true the page control is visible on screen.
public var visible = true
}
// ----------------------------
//
// AukPageIndicatorContainer.swift
//
// ----------------------------
import UIKit
/// View containing a UIPageControl object that shows the dots for present pages.
final class AukPageIndicatorContainer: UIView {
deinit {
pageControl?.removeTarget(self, action: #selector(AukPageIndicatorContainer.didTapPageControl(_:)),
for: UIControl.Event.valueChanged)
}
var didTapPageControlCallback: ((Int)->())?
var pageControl: UIPageControl? {
get {
if subviews.count == 0 { return nil }
return subviews[0] as? UIPageControl
}
}
// Layouts the view, creates and layouts the page control
func setup(_ settings: AukSettings, scrollView: UIScrollView) {
styleContainer(settings)
AukPageIndicatorContainer.layoutContainer(self, settings: settings, scrollView: scrollView)
let pageControl = createPageControl(settings)
AukPageIndicatorContainer.layoutPageControl(pageControl, superview: self, settings: settings)
updateVisibility()
}
// Update the number of pages showing in the page control
func updateNumberOfPages(_ numberOfPages: Int) {
pageControl?.numberOfPages = numberOfPages
updateVisibility()
}
// Update the current page in the page control
func updateCurrentPage(_ currentPageIndex: Int) {
pageControl?.currentPage = currentPageIndex
}
private func styleContainer(_ settings: AukSettings) {
backgroundColor = settings.pageControl.backgroundColor
layer.cornerRadius = CGFloat(settings.pageControl.cornerRadius)
}
private static func layoutContainer(_ pageIndicatorContainer: AukPageIndicatorContainer,
settings: AukSettings, scrollView: UIScrollView) {
if let superview = pageIndicatorContainer.superview {
pageIndicatorContainer.translatesAutoresizingMaskIntoConstraints = false
// Align bottom of the page view indicator with the bottom of the scroll view
iiAutolayoutConstraints.alignSameAttributes(pageIndicatorContainer, toItem: scrollView,
constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.bottom,
margin: CGFloat(-settings.pageControl.marginToScrollViewBottom))
// Center the page view indicator horizontally in relation to the scroll view
iiAutolayoutConstraints.alignSameAttributes(pageIndicatorContainer, toItem: scrollView,
constraintContainer: superview, attribute: NSLayoutConstraint.Attribute.centerX, margin: 0)
}
}
private func createPageControl(_ settings: AukSettings) -> UIPageControl {
let pageControl = UIPageControl()
if #available(*, iOS 9.0) {
// iOS 9+
} else {
// When using right-to-left language, flip the page control horizontally in iOS 8 and earlier.
// That will make it highlight the rightmost dot for the first page.
if RightToLeft.isRightToLeft(self) {
pageControl.transform = CGAffineTransform(scaleX: -1, y: 1)
}
}
pageControl.addTarget(self, action: #selector(AukPageIndicatorContainer.didTapPageControl(_:)),
for: UIControl.Event.valueChanged)
pageControl.pageIndicatorTintColor = settings.pageControl.pageIndicatorTintColor
pageControl.currentPageIndicatorTintColor = settings.pageControl.currentPageIndicatorTintColor
addSubview(pageControl)
return pageControl
}
@objc func didTapPageControl(_ control: UIPageControl) {
if let currentPage = pageControl?.currentPage {
didTapPageControlCallback?(currentPage)
}
}
private static func layoutPageControl(_ pageControl: UIPageControl, superview: UIView,
settings: AukSettings) {
pageControl.translatesAutoresizingMaskIntoConstraints = false
iiAutolayoutConstraints.fillParent(pageControl, parentView: superview,
margin: settings.pageControl.innerPadding.width, vertically: false)
iiAutolayoutConstraints.fillParent(pageControl, parentView: superview,
margin: settings.pageControl.innerPadding.height, vertically: true)
}
private func updateVisibility() {
if let pageControl = pageControl {
self.isHidden = pageControl.numberOfPages < 2
}
}
}
// ----------------------------
//
// AukAutoscroll.swift
//
// ----------------------------
import UIKit
/**
Starts and cancels the auto scrolling.
*/
struct AukAutoscroll {
var autoscrollTimer: AutoCancellingTimer?
mutating func startAutoScroll(_ scrollView: UIScrollView, delaySeconds: Double,
forward: Bool, cycle: Bool, animated: Bool, auk: Auk) {
// Assign the new instance of AutoCancellingTimer to autoscrollTimer
// The previous instance deinitializes and cancels its timer.
autoscrollTimer = AutoCancellingTimer(interval: delaySeconds, repeats: true) {
guard let currentPageIndex = auk.currentPageIndex else { return }
if forward {
AukScrollTo.scrollToNextPage(scrollView, cycle: cycle,
animated: animated, currentPageIndex: currentPageIndex,
numberOfPages: auk.numberOfPages)
} else {
AukScrollTo.scrollToPreviousPage(scrollView, cycle: cycle,
animated: animated, currentPageIndex: currentPageIndex,
numberOfPages: auk.numberOfPages)
}
}
}
mutating func stopAutoScroll() {
autoscrollTimer = nil // Cancels the timer on deinit
}
}
// ----------------------------
//
// AukScrollTo.swift
//
// ----------------------------
import UIKit
/**
Scrolling code.
*/
struct AukScrollTo {
static func scrollToPage(_ scrollView: UIScrollView, atIndex index: Int, animated: Bool,
numberOfPages: Int) {
let pageWidth = scrollView.bounds.size.width
scrollToPage(scrollView, atIndex: index, pageWidth: pageWidth, animated: animated,
numberOfPages: numberOfPages)
}
static func scrollToPage(_ scrollView: UIScrollView, atIndex index: Int, pageWidth: CGFloat,
animated: Bool, numberOfPages: Int) {
let offsetX = contentOffsetForPage(atIndex: index, pageWidth: pageWidth,
numberOfPages: numberOfPages, scrollView: scrollView)