MediaBrowserViewController.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. //
  2. // MediaBrowserViewController.swift
  3. // ATGMediaBrowser
  4. //
  5. // Created by Suraj Thomas K on 7/10/18.
  6. // Copyright © 2018 Al Tayer Group LLC.
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  9. // and associated documentation files (the "Software"), to deal in the Software without
  10. // restriction, including without limitation the rights to use, copy, modify, merge, publish,
  11. // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
  12. // Software is furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in all copies or
  15. // substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
  18. // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. //
  23. // MARK: - MediaBrowserViewControllerDataSource protocol
  24. /// Protocol to supply media browser contents.
  25. public protocol MediaBrowserViewControllerDataSource: class {
  26. /**
  27. Completion block for passing requested media image with details.
  28. - parameter index: Index of the requested media.
  29. - parameter image: Image to be passed back to media browser.
  30. - parameter zoomScale: Zoom scale to be applied to the image including min and max levels.
  31. - parameter error: Error received while fetching the media image.
  32. - note:
  33. Remember to pass the index received in the datasource method back.
  34. This index is used to set the image to the correct image view.
  35. */
  36. typealias CompletionBlock = (_ index: Int, _ image: UIImage?, _ zoomScale: ZoomScale?, _ error: Error?) -> Void
  37. /**
  38. Method to supply number of items to be shown in media browser.
  39. - parameter mediaBrowser: Reference to media browser object.
  40. - returns: An integer with number of items to be shown in media browser.
  41. */
  42. func numberOfItems(in mediaBrowser: MediaBrowserViewController) -> Int
  43. /**
  44. Method to supply image for specific index.
  45. - parameter mediaBrowser: Reference to media browser object.
  46. - parameter index: Index of the requested media.
  47. - parameter completion: Completion block to be executed on fetching the media image.
  48. */
  49. func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, imageAt index: Int, completion: @escaping CompletionBlock)
  50. /**
  51. This method is used to get the target frame into which the browser will perform the dismiss transition.
  52. - parameter mediaBrowser: Reference to media browser object.
  53. - note:
  54. If this method is not implemented, the media browser will perform slide up/down transition on dismissal.
  55. */
  56. func targetFrameForDismissal(_ mediaBrowser: MediaBrowserViewController) -> CGRect?
  57. }
  58. extension MediaBrowserViewControllerDataSource {
  59. public func targetFrameForDismissal(_ mediaBrowser: MediaBrowserViewController) -> CGRect? { return nil }
  60. }
  61. // MARK: - MediaBrowserViewControllerDelegate protocol
  62. public protocol MediaBrowserViewControllerDelegate: class {
  63. /**
  64. Method invoked on scrolling to next/previous media items.
  65. - parameter mediaBrowser: Reference to media browser object.
  66. - parameter index: Index of the newly focussed media item.
  67. - note:
  68. This method will not be called on first load, and will be called only on swiping left and right.
  69. */
  70. func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, didChangeFocusTo index: Int)
  71. }
  72. extension MediaBrowserViewControllerDelegate {
  73. public func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, didChangeFocusTo index: Int) {}
  74. }
  75. public class MediaBrowserViewController: UIViewController {
  76. // MARK: - Exposed Enumerations
  77. /**
  78. Enum to hold supported gesture directions.
  79. ```
  80. case horizontal
  81. case vertical
  82. ```
  83. */
  84. public enum GestureDirection {
  85. /// Horizontal (left - right) gestures.
  86. case horizontal
  87. /// Vertical (up - down) gestures.
  88. case vertical
  89. }
  90. /**
  91. Enum to hold supported browser styles.
  92. ```
  93. case linear
  94. case carousel
  95. ```
  96. */
  97. public enum BrowserStyle {
  98. /// Linear browser with *0* as first index and *numItems-1* as last index.
  99. case linear
  100. /// Carousel browser. The media items are repeated in a circular fashion.
  101. case carousel
  102. }
  103. /**
  104. Enum to hold supported content draw orders.
  105. ```
  106. case previousToNext
  107. case nextToPrevious
  108. ```
  109. - note:
  110. Remember that this is draw order, not positioning. This order decides which item will
  111. be above or below other items, when they overlap.
  112. */
  113. public enum ContentDrawOrder {
  114. /// In this mode, media items are rendered in [previous]-[current]-[next] order.
  115. case previousToNext
  116. /// In this mode, media items are rendered in [next]-[current]-[previous] order.
  117. case nextToPrevious
  118. }
  119. /**
  120. Struct to hold support for customize title style
  121. ```
  122. font
  123. textColor
  124. ```
  125. */
  126. public struct TitleStyle {
  127. /// Title style font
  128. public var font: UIFont = UIFont.preferredFont(forTextStyle: .subheadline)
  129. /// Title style text color.
  130. public var textColor: UIColor = .white
  131. }
  132. // MARK: - Exposed variables
  133. /// Data-source object to supply media browser contents.
  134. public weak var dataSource: MediaBrowserViewControllerDataSource?
  135. /// Delegate object to get callbacks on media browser events.
  136. public weak var delegate: MediaBrowserViewControllerDelegate?
  137. /// Gesture direction. Default is `horizontal`.
  138. public var gestureDirection: GestureDirection = .horizontal
  139. /// Content transformer closure. Default is `horizontalMoveInOut`.
  140. public var contentTransformer: ContentTransformer = DefaultContentTransformers.horizontalMoveInOut {
  141. didSet {
  142. MediaContentView.contentTransformer = contentTransformer
  143. contentViews.forEach({ $0.updateTransform() })
  144. }
  145. }
  146. /// Content draw order. Default is `previousToNext`.
  147. public var drawOrder: ContentDrawOrder = .previousToNext {
  148. didSet {
  149. if oldValue != drawOrder {
  150. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  151. }
  152. }
  153. }
  154. /// Browser style. Default is carousel.
  155. public var browserStyle: BrowserStyle = .carousel
  156. /// Gap between consecutive media items. Default is `50.0`.
  157. public var gapBetweenMediaViews: CGFloat = Constants.gapBetweenContents {
  158. didSet {
  159. MediaContentView.interItemSpacing = gapBetweenMediaViews
  160. contentViews.forEach({ $0.updateTransform() })
  161. }
  162. }
  163. /// Variable to set title style in media browser.
  164. public var titleStyle: TitleStyle = TitleStyle() {
  165. didSet {
  166. configureTitleLabel()
  167. }
  168. }
  169. /// Variable to set title in media browser
  170. public override var title: String? {
  171. didSet {
  172. titleLabel.text = title
  173. }
  174. }
  175. /// Variable to hide/show title control in media browser. Default is false.
  176. public var shouldShowTitle: Bool = false {
  177. didSet {
  178. titleLabel.isHidden = !shouldShowTitle
  179. }
  180. }
  181. /// Variable to hide/show page control in media browser.
  182. public var shouldShowPageControl: Bool = true {
  183. didSet {
  184. pageControl.isHidden = !shouldShowPageControl
  185. }
  186. }
  187. /// Variable to hide/show controls(close & page control). Default is false.
  188. public var hideControls: Bool = false {
  189. didSet {
  190. hideControlViews(hideControls)
  191. }
  192. }
  193. /**
  194. Variable to schedule/cancel auto-hide controls(close & page control). Default is false.
  195. Default delay is `3.0` seconds.
  196. - todo: Update to accept auto-hide-delay.
  197. */
  198. public var autoHideControls: Bool = false {
  199. didSet {
  200. if autoHideControls {
  201. DispatchQueue.main.asyncAfter(
  202. deadline: .now() + Constants.controlHideDelay,
  203. execute: controlToggleTask
  204. )
  205. } else {
  206. controlToggleTask.cancel()
  207. }
  208. }
  209. }
  210. /// Enable or disable interactive dismissal. Default is enabled.
  211. public var enableInteractiveDismissal: Bool = true
  212. /// Item index of the current item. In range `0..<numMediaItems`
  213. public var currentItemIndex: Int {
  214. return sanitizeIndex(index)
  215. }
  216. // MARK: - Private Enumerations
  217. private enum Constants {
  218. static let gapBetweenContents: CGFloat = 50.0
  219. static let minimumVelocity: CGFloat = 15.0
  220. static let minimumTranslation: CGFloat = 0.1
  221. static let animationDuration = 0.3
  222. static let updateFrameRate: CGFloat = 60.0
  223. static let bounceFactor: CGFloat = 0.1
  224. static let controlHideDelay = 3.0
  225. enum Close {
  226. static let top: CGFloat = 8.0
  227. static let trailing: CGFloat = -8.0
  228. static let height: CGFloat = 30.0
  229. static let minWidth: CGFloat = 30.0
  230. static let contentInsets = UIEdgeInsets(top: 0.0, left: 8.0, bottom: 0.0, right: 8.0)
  231. static let borderWidth: CGFloat = 2.0
  232. static let borderColor: UIColor = .white
  233. static let title = "Close"
  234. }
  235. enum PageControl {
  236. static let bottom: CGFloat = -10.0
  237. static let tintColor: UIColor = .lightGray
  238. static let selectedTintColor: UIColor = .white
  239. }
  240. enum Title {
  241. static let top: CGFloat = 16.0
  242. static let rect: CGRect = CGRect(x: 0, y: 0, width: 30, height: 30)
  243. }
  244. }
  245. // MARK: - Private variables
  246. private(set) var index: Int = 0 {
  247. didSet {
  248. pageControl.currentPage = index
  249. }
  250. }
  251. private var contentViews: [MediaContentView] = []
  252. private var controlViews: [UIView] = []
  253. lazy private var controlToggleTask: DispatchWorkItem = { [unowned self] in
  254. let item = DispatchWorkItem {
  255. self.hideControls = true
  256. }
  257. return item
  258. }()
  259. lazy private var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
  260. let gesture = UITapGestureRecognizer()
  261. gesture.numberOfTapsRequired = 1
  262. gesture.numberOfTouchesRequired = 1
  263. gesture.delegate = self
  264. gesture.addTarget(self, action: #selector(tapGestureEvent(_:)))
  265. return gesture
  266. }()
  267. private var previousTranslation: CGPoint = .zero
  268. private var timer: Timer?
  269. private var distanceToMove: CGFloat = 0.0
  270. lazy private var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
  271. let gesture = UIPanGestureRecognizer()
  272. gesture.minimumNumberOfTouches = 1
  273. gesture.maximumNumberOfTouches = 1
  274. gesture.delegate = self
  275. gesture.addTarget(self, action: #selector(panGestureEvent(_:)))
  276. return gesture
  277. }()
  278. lazy internal private(set) var mediaContainerView: UIView = { [unowned self] in
  279. let container = UIView()
  280. container.backgroundColor = .clear
  281. return container
  282. }()
  283. lazy private var pageControl: UIPageControl = { [unowned self] in
  284. let pageControl = UIPageControl()
  285. pageControl.hidesForSinglePage = true
  286. pageControl.numberOfPages = numMediaItems
  287. pageControl.currentPageIndicatorTintColor = Constants.PageControl.selectedTintColor
  288. pageControl.tintColor = Constants.PageControl.tintColor
  289. pageControl.currentPage = index
  290. return pageControl
  291. }()
  292. lazy var titleLabel: UILabel = {
  293. let label = UILabel(frame: Constants.Title.rect)
  294. label.font = self.titleStyle.font
  295. label.textColor = self.titleStyle.textColor
  296. label.textAlignment = .center
  297. return label
  298. }()
  299. private var numMediaItems = 0
  300. private lazy var dismissController = DismissAnimationController(
  301. gestureDirection: gestureDirection,
  302. viewController: self
  303. )
  304. // MARK: - Public methods
  305. /// Invoking this method reloads the contents media browser.
  306. public func reloadContentViews() {
  307. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  308. if shouldShowPageControl {
  309. pageControl.numberOfPages = numMediaItems
  310. }
  311. for contentView in contentViews {
  312. updateContents(of: contentView)
  313. }
  314. }
  315. // MARK: - Initializers
  316. public init(
  317. index: Int = 0,
  318. dataSource: MediaBrowserViewControllerDataSource,
  319. delegate: MediaBrowserViewControllerDelegate? = nil
  320. ) {
  321. self.index = index
  322. self.dataSource = dataSource
  323. self.delegate = delegate
  324. super.init(nibName: nil, bundle: nil)
  325. initialize()
  326. }
  327. public required init?(coder aDecoder: NSCoder) {
  328. super.init(coder: aDecoder)
  329. initialize()
  330. }
  331. private func initialize() {
  332. view.backgroundColor = .clear
  333. modalPresentationStyle = .custom
  334. modalTransitionStyle = .crossDissolve
  335. }
  336. }
  337. // MARK: - View Lifecycle and Events
  338. extension MediaBrowserViewController {
  339. override public var prefersStatusBarHidden: Bool {
  340. return true
  341. }
  342. override public func viewDidLoad() {
  343. super.viewDidLoad()
  344. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  345. populateContentViews()
  346. addPageControl()
  347. addTitleLabel()
  348. view.addGestureRecognizer(panGestureRecognizer)
  349. view.addGestureRecognizer(tapGestureRecognizer)
  350. }
  351. override public func viewDidAppear(_ animated: Bool) {
  352. super.viewDidAppear(animated)
  353. contentViews.forEach({ $0.updateTransform() })
  354. }
  355. override public func viewWillDisappear(_ animated: Bool) {
  356. super.viewWillDisappear(animated)
  357. if !controlToggleTask.isCancelled {
  358. controlToggleTask.cancel()
  359. }
  360. }
  361. public override func viewWillTransition(
  362. to size: CGSize,
  363. with coordinator: UIViewControllerTransitionCoordinator
  364. ) {
  365. coordinator.animate(alongsideTransition: { context in
  366. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  367. }, completion: nil)
  368. super.viewWillTransition(to: size, with: coordinator)
  369. }
  370. private func populateContentViews() {
  371. view.addSubview(mediaContainerView)
  372. mediaContainerView.translatesAutoresizingMaskIntoConstraints = false
  373. NSLayoutConstraint.activate([
  374. mediaContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  375. mediaContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  376. mediaContainerView.topAnchor.constraint(equalTo: view.topAnchor),
  377. mediaContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  378. ])
  379. MediaContentView.interItemSpacing = gapBetweenMediaViews
  380. MediaContentView.contentTransformer = contentTransformer
  381. contentViews.forEach({ $0.removeFromSuperview() })
  382. contentViews.removeAll()
  383. for i in -1...1 {
  384. let mediaView = MediaContentView(
  385. index: i + index,
  386. position: CGFloat(i),
  387. frame: view.bounds
  388. )
  389. mediaContainerView.addSubview(mediaView)
  390. mediaView.translatesAutoresizingMaskIntoConstraints = false
  391. NSLayoutConstraint.activate([
  392. mediaView.leadingAnchor.constraint(equalTo: mediaContainerView.leadingAnchor),
  393. mediaView.trailingAnchor.constraint(equalTo: mediaContainerView.trailingAnchor),
  394. mediaView.topAnchor.constraint(equalTo: mediaContainerView.topAnchor),
  395. mediaView.bottomAnchor.constraint(equalTo: mediaContainerView.bottomAnchor)
  396. ])
  397. contentViews.append(mediaView)
  398. if numMediaItems > 0 {
  399. updateContents(of: mediaView)
  400. }
  401. }
  402. if drawOrder == .nextToPrevious {
  403. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  404. }
  405. }
  406. private func addPageControl() {
  407. view.addSubview(pageControl)
  408. pageControl.translatesAutoresizingMaskIntoConstraints = false
  409. var bottomAnchor = view.bottomAnchor
  410. if #available(iOS 11.0, *) {
  411. if view.responds(to: #selector(getter: UIView.safeAreaLayoutGuide)) {
  412. bottomAnchor = view.safeAreaLayoutGuide.bottomAnchor
  413. }
  414. }
  415. NSLayoutConstraint.activate([
  416. pageControl.bottomAnchor.constraint(equalTo: bottomAnchor, constant: Constants.PageControl.bottom),
  417. pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor)
  418. ])
  419. controlViews.append(pageControl)
  420. }
  421. private func addTitleLabel() {
  422. view.addSubview(titleLabel)
  423. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  424. var topAnchor = view.topAnchor
  425. if #available(iOS 11.0, *) {
  426. if view.responds(to: #selector(getter: UIView.safeAreaLayoutGuide)) {
  427. topAnchor = view.safeAreaLayoutGuide.topAnchor
  428. }
  429. }
  430. NSLayoutConstraint.activate([
  431. titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: Constants.Title.top),
  432. titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
  433. ])
  434. controlViews.append(titleLabel)
  435. }
  436. private func configureTitleLabel() {
  437. titleLabel.font = self.titleStyle.font
  438. titleLabel.textColor = self.titleStyle.textColor
  439. }
  440. private func hideControlViews(_ hide: Bool) {
  441. self.controlViews.forEach { $0.alpha = hide ? 0.0 : 1.0 }
  442. /*
  443. UIView.animate(
  444. withDuration: Constants.animationDuration,
  445. delay: 0.0,
  446. options: .beginFromCurrentState,
  447. animations: {
  448. self.controlViews.forEach { $0.alpha = hide ? 0.0 : 1.0 }
  449. },
  450. completion: nil
  451. )
  452. */
  453. }
  454. @objc private func didTapOnClose(_ sender: UIButton) {
  455. if let targetFrame = dataSource?.targetFrameForDismissal(self) {
  456. dismissController.image = sourceImage()
  457. dismissController.beginTransition()
  458. dismissController.animateToTargetFrame(targetFrame)
  459. } else {
  460. dismiss(animated: true, completion: nil)
  461. }
  462. }
  463. }
  464. // MARK: - Gesture Recognizers
  465. extension MediaBrowserViewController {
  466. @objc private func panGestureEvent(_ recognizer: UIPanGestureRecognizer) {
  467. if dismissController.interactionInProgress {
  468. dismissController.handleInteractiveTransition(recognizer)
  469. return
  470. }
  471. guard numMediaItems > 0 else {
  472. return
  473. }
  474. let translation = recognizer.translation(in: view)
  475. switch recognizer.state {
  476. case .began:
  477. previousTranslation = translation
  478. distanceToMove = 0.0
  479. timer?.invalidate()
  480. timer = nil
  481. case .changed:
  482. moveViews(by: CGPoint(x: translation.x - previousTranslation.x, y: translation.y - previousTranslation.y))
  483. case .ended, .failed, .cancelled:
  484. let velocity = recognizer.velocity(in: view)
  485. var viewsCopy = contentViews
  486. let previousView = viewsCopy.removeFirst()
  487. let middleView = viewsCopy.removeFirst()
  488. let nextView = viewsCopy.removeFirst()
  489. var toMove: CGFloat = 0.0
  490. let directionalVelocity = gestureDirection == .horizontal ? velocity.x : velocity.y
  491. if abs(directionalVelocity) < Constants.minimumVelocity &&
  492. abs(middleView.position) < Constants.minimumTranslation {
  493. toMove = -middleView.position
  494. } else if directionalVelocity < 0.0 {
  495. if middleView.position >= 0.0 {
  496. toMove = -middleView.position
  497. } else {
  498. toMove = -nextView.position
  499. }
  500. } else {
  501. if middleView.position <= 0.0 {
  502. toMove = -middleView.position
  503. } else {
  504. toMove = -previousView.position
  505. }
  506. }
  507. if browserStyle == .linear || numMediaItems <= 1 {
  508. if (middleView.index == 0 && ((middleView.position + toMove) > 0.0)) ||
  509. (middleView.index == (numMediaItems - 1) && (middleView.position + toMove) < 0.0) {
  510. toMove = -middleView.position
  511. }
  512. }
  513. distanceToMove = toMove
  514. if timer == nil {
  515. timer = Timer.scheduledTimer(
  516. timeInterval: 1.0/Double(Constants.updateFrameRate),
  517. target: self,
  518. selector: #selector(update(_:)),
  519. userInfo: nil,
  520. repeats: true
  521. )
  522. }
  523. default:
  524. break
  525. }
  526. previousTranslation = translation
  527. }
  528. @objc private func tapGestureEvent(_ recognizer: UITapGestureRecognizer) {
  529. guard !dismissController.interactionInProgress else {
  530. return
  531. }
  532. if !controlToggleTask.isCancelled {
  533. controlToggleTask.cancel()
  534. }
  535. hideControls = !hideControls
  536. }
  537. }
  538. // MARK: - Updating View Positions
  539. extension MediaBrowserViewController {
  540. @objc private func update(_ timeInterval: TimeInterval) {
  541. guard distanceToMove != 0.0 else {
  542. timer?.invalidate()
  543. timer = nil
  544. return
  545. }
  546. let distance = distanceToMove / (Constants.updateFrameRate * 0.1)
  547. distanceToMove -= distance
  548. moveViewsNormalized(by: CGPoint(x: distance, y: distance))
  549. let translation = CGPoint(
  550. x: distance * (view.frame.size.width + gapBetweenMediaViews),
  551. y: distance * (view.frame.size.height + gapBetweenMediaViews)
  552. )
  553. let directionalTranslation = (gestureDirection == .horizontal) ? translation.x : translation.y
  554. if abs(directionalTranslation) < 0.1 {
  555. moveViewsNormalized(by: CGPoint(x: distanceToMove, y: distanceToMove))
  556. distanceToMove = 0.0
  557. timer?.invalidate()
  558. timer = nil
  559. }
  560. }
  561. private func moveViews(by translation: CGPoint) {
  562. let viewSizeIncludingGap = CGSize(
  563. width: view.frame.size.width + gapBetweenMediaViews,
  564. height: view.frame.size.height + gapBetweenMediaViews
  565. )
  566. let normalizedTranslation = calculateNormalizedTranslation(
  567. translation: translation,
  568. viewSize: viewSizeIncludingGap
  569. )
  570. moveViewsNormalized(by: normalizedTranslation)
  571. }
  572. private func moveViewsNormalized(by normalizedTranslation: CGPoint) {
  573. let isGestureHorizontal = (gestureDirection == .horizontal)
  574. contentViews.forEach({
  575. $0.position += isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  576. })
  577. var viewsCopy = contentViews
  578. let previousView = viewsCopy.removeFirst()
  579. let middleView = viewsCopy.removeFirst()
  580. let nextView = viewsCopy.removeFirst()
  581. let viewSizeIncludingGap = CGSize(
  582. width: view.frame.size.width + gapBetweenMediaViews,
  583. height: view.frame.size.height + gapBetweenMediaViews
  584. )
  585. let viewSize = isGestureHorizontal ? viewSizeIncludingGap.width : viewSizeIncludingGap.height
  586. let normalizedGap = gapBetweenMediaViews/viewSize
  587. let normalizedCenter = (middleView.frame.size.width / viewSize) * 0.5
  588. let viewCount = contentViews.count
  589. if middleView.position < -(normalizedGap + normalizedCenter) {
  590. index = sanitizeIndex(index + 1)
  591. // Previous item is taken and placed on right/down most side
  592. previousView.position += CGFloat(viewCount)
  593. previousView.index += viewCount
  594. updateContents(of: previousView)
  595. contentViews.removeFirst()
  596. contentViews.append(previousView)
  597. switch drawOrder {
  598. case .previousToNext:
  599. mediaContainerView.bringSubviewToFront(previousView)
  600. case .nextToPrevious:
  601. mediaContainerView.sendSubviewToBack(previousView)
  602. }
  603. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  604. } else if middleView.position > (1 + normalizedGap - normalizedCenter) {
  605. index = sanitizeIndex(index - 1)
  606. // Next item is taken and placed on left/top most side
  607. nextView.position -= CGFloat(viewCount)
  608. nextView.index -= viewCount
  609. updateContents(of: nextView)
  610. contentViews.removeLast()
  611. contentViews.insert(nextView, at: 0)
  612. switch drawOrder {
  613. case .previousToNext:
  614. mediaContainerView.sendSubviewToBack(nextView)
  615. case .nextToPrevious:
  616. mediaContainerView.bringSubviewToFront(nextView)
  617. }
  618. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  619. }
  620. }
  621. private func calculateNormalizedTranslation(translation: CGPoint, viewSize: CGSize) -> CGPoint {
  622. guard let middleView = mediaView(at: 1) else {
  623. return .zero
  624. }
  625. var normalizedTranslation = CGPoint(
  626. x: (translation.x)/viewSize.width,
  627. y: (translation.y)/viewSize.height
  628. )
  629. if browserStyle != .carousel || numMediaItems <= 1 {
  630. let isGestureHorizontal = (gestureDirection == .horizontal)
  631. let directionalTranslation = isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  632. if (middleView.index == 0 && ((middleView.position + directionalTranslation) > 0.0)) ||
  633. (middleView.index == (numMediaItems - 1) && (middleView.position + directionalTranslation) < 0.0) {
  634. if isGestureHorizontal {
  635. normalizedTranslation.x *= Constants.bounceFactor
  636. } else {
  637. normalizedTranslation.y *= Constants.bounceFactor
  638. }
  639. }
  640. }
  641. return normalizedTranslation
  642. }
  643. private func updateContents(of contentView: MediaContentView) {
  644. contentView.image = nil
  645. let convertedIndex = sanitizeIndex(contentView.index)
  646. contentView.isLoading = true
  647. dataSource?.mediaBrowser(
  648. self,
  649. imageAt: convertedIndex,
  650. completion: { [weak self] (index, image, zoom, _) in
  651. guard let strongSelf = self else {
  652. return
  653. }
  654. if index == strongSelf.sanitizeIndex(contentView.index) {
  655. if image != nil {
  656. contentView.image = image
  657. contentView.zoomLevels = zoom
  658. }
  659. contentView.isLoading = false
  660. }
  661. }
  662. )
  663. }
  664. private func sanitizeIndex(_ index: Int) -> Int {
  665. let newIndex = index % numMediaItems
  666. if newIndex < 0 {
  667. return newIndex + numMediaItems
  668. }
  669. return newIndex
  670. }
  671. private func sourceImage() -> UIImage? {
  672. return mediaView(at: 1)?.image
  673. }
  674. private func mediaView(at index: Int) -> MediaContentView? {
  675. guard index < contentViews.count else {
  676. assertionFailure("Content views does not have this many views. : \(index)")
  677. return nil
  678. }
  679. return contentViews[index]
  680. }
  681. }
  682. // MARK: - UIGestureRecognizerDelegate
  683. extension MediaBrowserViewController: UIGestureRecognizerDelegate {
  684. public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  685. guard enableInteractiveDismissal else {
  686. return true
  687. }
  688. let middleView = mediaView(at: 1)
  689. if middleView?.zoomScale == middleView?.zoomLevels?.minimumZoomScale,
  690. let recognizer = gestureRecognizer as? UIPanGestureRecognizer {
  691. let translation = recognizer.translation(in: recognizer.view)
  692. if gestureDirection == .horizontal {
  693. dismissController.interactionInProgress = abs(translation.y) > abs(translation.x)
  694. } else {
  695. dismissController.interactionInProgress = abs(translation.x) > abs(translation.y)
  696. }
  697. if dismissController.interactionInProgress {
  698. dismissController.image = sourceImage()
  699. }
  700. }
  701. return true
  702. }
  703. public func gestureRecognizer(
  704. _ gestureRecognizer: UIGestureRecognizer,
  705. shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
  706. ) -> Bool {
  707. if gestureRecognizer is UIPanGestureRecognizer,
  708. let scrollView = otherGestureRecognizer.view as? MediaContentView {
  709. return scrollView.zoomScale == 1.0
  710. }
  711. return false
  712. }
  713. public func gestureRecognizer(
  714. _ gestureRecognizer: UIGestureRecognizer,
  715. shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer
  716. ) -> Bool {
  717. if gestureRecognizer is UITapGestureRecognizer {
  718. return otherGestureRecognizer.view is MediaContentView
  719. }
  720. return false
  721. }
  722. }