MediaBrowserViewController.swift 30 KB

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