MediaBrowserViewController.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. public var containerView = UIView()
  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. containerView: UIView
  322. ) {
  323. self.index = index
  324. self.dataSource = dataSource
  325. self.delegate = delegate
  326. self.containerView = containerView
  327. super.init(nibName: nil, bundle: nil)
  328. initialize()
  329. }
  330. public required init?(coder aDecoder: NSCoder) {
  331. super.init(coder: aDecoder)
  332. initialize()
  333. }
  334. private func initialize() {
  335. view.backgroundColor = .clear
  336. modalPresentationStyle = .custom
  337. modalTransitionStyle = .crossDissolve
  338. }
  339. public func changeInViewSize(to size: CGSize) {
  340. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  341. }
  342. }
  343. // MARK: - View Lifecycle and Events
  344. extension MediaBrowserViewController {
  345. override public var prefersStatusBarHidden: Bool {
  346. return true
  347. }
  348. override public func viewDidLoad() {
  349. super.viewDidLoad()
  350. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  351. populateContentViews()
  352. addPageControl()
  353. addTitleLabel()
  354. view.addGestureRecognizer(panGestureRecognizer)
  355. view.addGestureRecognizer(tapGestureRecognizer)
  356. }
  357. override public func viewDidAppear(_ animated: Bool) {
  358. super.viewDidAppear(animated)
  359. contentViews.forEach({ $0.updateTransform() })
  360. }
  361. override public func viewWillDisappear(_ animated: Bool) {
  362. super.viewWillDisappear(animated)
  363. if !controlToggleTask.isCancelled {
  364. controlToggleTask.cancel()
  365. }
  366. }
  367. public override func viewWillTransition(
  368. to size: CGSize,
  369. with coordinator: UIViewControllerTransitionCoordinator
  370. ) {
  371. coordinator.animate(alongsideTransition: { context in
  372. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  373. }, completion: nil)
  374. super.viewWillTransition(to: size, with: coordinator)
  375. }
  376. private func populateContentViews() {
  377. view.addSubview(mediaContainerView)
  378. mediaContainerView.translatesAutoresizingMaskIntoConstraints = false
  379. NSLayoutConstraint.activate([
  380. mediaContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  381. mediaContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  382. mediaContainerView.topAnchor.constraint(equalTo: view.topAnchor),
  383. mediaContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  384. ])
  385. MediaContentView.interItemSpacing = gapBetweenMediaViews
  386. MediaContentView.contentTransformer = contentTransformer
  387. contentViews.forEach({ $0.removeFromSuperview() })
  388. contentViews.removeAll()
  389. for i in -1...1 {
  390. let mediaView = MediaContentView(
  391. index: i + index,
  392. position: CGFloat(i),
  393. frame: view.bounds
  394. )
  395. mediaContainerView.addSubview(mediaView)
  396. mediaView.translatesAutoresizingMaskIntoConstraints = false
  397. NSLayoutConstraint.activate([
  398. mediaView.leadingAnchor.constraint(equalTo: mediaContainerView.leadingAnchor),
  399. mediaView.trailingAnchor.constraint(equalTo: mediaContainerView.trailingAnchor),
  400. mediaView.topAnchor.constraint(equalTo: mediaContainerView.topAnchor),
  401. mediaView.bottomAnchor.constraint(equalTo: mediaContainerView.bottomAnchor)
  402. ])
  403. contentViews.append(mediaView)
  404. if numMediaItems > 0 {
  405. updateContents(of: mediaView)
  406. }
  407. }
  408. if drawOrder == .nextToPrevious {
  409. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  410. }
  411. }
  412. private func addPageControl() {
  413. view.addSubview(pageControl)
  414. pageControl.translatesAutoresizingMaskIntoConstraints = false
  415. var bottomAnchor = view.bottomAnchor
  416. if #available(iOS 11.0, *) {
  417. if view.responds(to: #selector(getter: UIView.safeAreaLayoutGuide)) {
  418. bottomAnchor = view.safeAreaLayoutGuide.bottomAnchor
  419. }
  420. }
  421. NSLayoutConstraint.activate([
  422. pageControl.bottomAnchor.constraint(equalTo: bottomAnchor, constant: Constants.PageControl.bottom),
  423. pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor)
  424. ])
  425. controlViews.append(pageControl)
  426. }
  427. private func addTitleLabel() {
  428. view.addSubview(titleLabel)
  429. titleLabel.translatesAutoresizingMaskIntoConstraints = false
  430. var topAnchor = view.topAnchor
  431. if #available(iOS 11.0, *) {
  432. if view.responds(to: #selector(getter: UIView.safeAreaLayoutGuide)) {
  433. topAnchor = view.safeAreaLayoutGuide.topAnchor
  434. }
  435. }
  436. NSLayoutConstraint.activate([
  437. titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: Constants.Title.top),
  438. titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
  439. ])
  440. controlViews.append(titleLabel)
  441. }
  442. private func configureTitleLabel() {
  443. titleLabel.font = self.titleStyle.font
  444. titleLabel.textColor = self.titleStyle.textColor
  445. }
  446. private func hideControlViews(_ hide: Bool) {
  447. self.controlViews.forEach { $0.alpha = hide ? 0.0 : 1.0 }
  448. /*
  449. UIView.animate(
  450. withDuration: Constants.animationDuration,
  451. delay: 0.0,
  452. options: .beginFromCurrentState,
  453. animations: {
  454. self.controlViews.forEach { $0.alpha = hide ? 0.0 : 1.0 }
  455. },
  456. completion: nil
  457. )
  458. */
  459. }
  460. @objc private func didTapOnClose(_ sender: UIButton) {
  461. if let targetFrame = dataSource?.targetFrameForDismissal(self) {
  462. dismissController.image = sourceImage()
  463. dismissController.beginTransition()
  464. dismissController.animateToTargetFrame(targetFrame)
  465. } else {
  466. dismiss(animated: true, completion: nil)
  467. }
  468. }
  469. }
  470. // MARK: - Gesture Recognizers
  471. extension MediaBrowserViewController {
  472. @objc private func panGestureEvent(_ recognizer: UIPanGestureRecognizer) {
  473. if dismissController.interactionInProgress {
  474. dismissController.handleInteractiveTransition(recognizer)
  475. return
  476. }
  477. guard numMediaItems > 0 else {
  478. return
  479. }
  480. let translation = recognizer.translation(in: view)
  481. switch recognizer.state {
  482. case .began:
  483. previousTranslation = translation
  484. distanceToMove = 0.0
  485. timer?.invalidate()
  486. timer = nil
  487. case .changed:
  488. moveViews(by: CGPoint(x: translation.x - previousTranslation.x, y: translation.y - previousTranslation.y))
  489. case .ended, .failed, .cancelled:
  490. let velocity = recognizer.velocity(in: view)
  491. var viewsCopy = contentViews
  492. let previousView = viewsCopy.removeFirst()
  493. let middleView = viewsCopy.removeFirst()
  494. let nextView = viewsCopy.removeFirst()
  495. var toMove: CGFloat = 0.0
  496. let directionalVelocity = gestureDirection == .horizontal ? velocity.x : velocity.y
  497. if abs(directionalVelocity) < Constants.minimumVelocity &&
  498. abs(middleView.position) < Constants.minimumTranslation {
  499. toMove = -middleView.position
  500. } else if directionalVelocity < 0.0 {
  501. if middleView.position >= 0.0 {
  502. toMove = -middleView.position
  503. } else {
  504. toMove = -nextView.position
  505. }
  506. } else {
  507. if middleView.position <= 0.0 {
  508. toMove = -middleView.position
  509. } else {
  510. toMove = -previousView.position
  511. }
  512. }
  513. if browserStyle == .linear || numMediaItems <= 1 {
  514. if (middleView.index == 0 && ((middleView.position + toMove) > 0.0)) ||
  515. (middleView.index == (numMediaItems - 1) && (middleView.position + toMove) < 0.0) {
  516. toMove = -middleView.position
  517. }
  518. }
  519. distanceToMove = toMove
  520. if timer == nil {
  521. timer = Timer.scheduledTimer(
  522. timeInterval: 1.0/Double(Constants.updateFrameRate),
  523. target: self,
  524. selector: #selector(update(_:)),
  525. userInfo: nil,
  526. repeats: true
  527. )
  528. }
  529. default:
  530. break
  531. }
  532. previousTranslation = translation
  533. }
  534. @objc private func tapGestureEvent(_ recognizer: UITapGestureRecognizer) {
  535. guard !dismissController.interactionInProgress else {
  536. return
  537. }
  538. if !controlToggleTask.isCancelled {
  539. controlToggleTask.cancel()
  540. }
  541. hideControls = !hideControls
  542. }
  543. }
  544. // MARK: - Updating View Positions
  545. extension MediaBrowserViewController {
  546. @objc private func update(_ timeInterval: TimeInterval) {
  547. guard distanceToMove != 0.0 else {
  548. timer?.invalidate()
  549. timer = nil
  550. return
  551. }
  552. let distance = distanceToMove / (Constants.updateFrameRate * 0.1)
  553. distanceToMove -= distance
  554. moveViewsNormalized(by: CGPoint(x: distance, y: distance))
  555. let translation = CGPoint(
  556. x: distance * (view.frame.size.width + gapBetweenMediaViews),
  557. y: distance * (view.frame.size.height + gapBetweenMediaViews)
  558. )
  559. let directionalTranslation = (gestureDirection == .horizontal) ? translation.x : translation.y
  560. if abs(directionalTranslation) < 0.1 {
  561. moveViewsNormalized(by: CGPoint(x: distanceToMove, y: distanceToMove))
  562. distanceToMove = 0.0
  563. timer?.invalidate()
  564. timer = nil
  565. }
  566. }
  567. private func moveViews(by translation: CGPoint) {
  568. let viewSizeIncludingGap = CGSize(
  569. width: view.frame.size.width + gapBetweenMediaViews,
  570. height: view.frame.size.height + gapBetweenMediaViews
  571. )
  572. let normalizedTranslation = calculateNormalizedTranslation(
  573. translation: translation,
  574. viewSize: viewSizeIncludingGap
  575. )
  576. moveViewsNormalized(by: normalizedTranslation)
  577. }
  578. private func moveViewsNormalized(by normalizedTranslation: CGPoint) {
  579. let isGestureHorizontal = (gestureDirection == .horizontal)
  580. contentViews.forEach({
  581. $0.position += isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  582. })
  583. var viewsCopy = contentViews
  584. let previousView = viewsCopy.removeFirst()
  585. let middleView = viewsCopy.removeFirst()
  586. let nextView = viewsCopy.removeFirst()
  587. let viewSizeIncludingGap = CGSize(
  588. width: view.frame.size.width + gapBetweenMediaViews,
  589. height: view.frame.size.height + gapBetweenMediaViews
  590. )
  591. let viewSize = isGestureHorizontal ? viewSizeIncludingGap.width : viewSizeIncludingGap.height
  592. let normalizedGap = gapBetweenMediaViews/viewSize
  593. let normalizedCenter = (middleView.frame.size.width / viewSize) * 0.5
  594. let viewCount = contentViews.count
  595. if middleView.position < -(normalizedGap + normalizedCenter) {
  596. index = sanitizeIndex(index + 1)
  597. // Previous item is taken and placed on right/down most side
  598. previousView.position += CGFloat(viewCount)
  599. previousView.index += viewCount
  600. updateContents(of: previousView)
  601. contentViews.removeFirst()
  602. contentViews.append(previousView)
  603. switch drawOrder {
  604. case .previousToNext:
  605. mediaContainerView.bringSubviewToFront(previousView)
  606. case .nextToPrevious:
  607. mediaContainerView.sendSubviewToBack(previousView)
  608. }
  609. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  610. } else if middleView.position > (1 + normalizedGap - normalizedCenter) {
  611. index = sanitizeIndex(index - 1)
  612. // Next item is taken and placed on left/top most side
  613. nextView.position -= CGFloat(viewCount)
  614. nextView.index -= viewCount
  615. updateContents(of: nextView)
  616. contentViews.removeLast()
  617. contentViews.insert(nextView, at: 0)
  618. switch drawOrder {
  619. case .previousToNext:
  620. mediaContainerView.sendSubviewToBack(nextView)
  621. case .nextToPrevious:
  622. mediaContainerView.bringSubviewToFront(nextView)
  623. }
  624. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  625. }
  626. }
  627. private func calculateNormalizedTranslation(translation: CGPoint, viewSize: CGSize) -> CGPoint {
  628. guard let middleView = mediaView(at: 1) else {
  629. return .zero
  630. }
  631. var normalizedTranslation = CGPoint(
  632. x: (translation.x)/viewSize.width,
  633. y: (translation.y)/viewSize.height
  634. )
  635. if browserStyle != .carousel || numMediaItems <= 1 {
  636. let isGestureHorizontal = (gestureDirection == .horizontal)
  637. let directionalTranslation = isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  638. if (middleView.index == 0 && ((middleView.position + directionalTranslation) > 0.0)) ||
  639. (middleView.index == (numMediaItems - 1) && (middleView.position + directionalTranslation) < 0.0) {
  640. if isGestureHorizontal {
  641. normalizedTranslation.x *= Constants.bounceFactor
  642. } else {
  643. normalizedTranslation.y *= Constants.bounceFactor
  644. }
  645. }
  646. }
  647. return normalizedTranslation
  648. }
  649. private func updateContents(of contentView: MediaContentView) {
  650. contentView.image = nil
  651. let convertedIndex = sanitizeIndex(contentView.index)
  652. contentView.isLoading = true
  653. dataSource?.mediaBrowser(
  654. self,
  655. imageAt: convertedIndex,
  656. completion: { [weak self] (index, image, zoom, _) in
  657. guard let strongSelf = self else {
  658. return
  659. }
  660. if index == strongSelf.sanitizeIndex(contentView.index) {
  661. if image != nil {
  662. contentView.image = image
  663. contentView.zoomLevels = zoom
  664. }
  665. contentView.isLoading = false
  666. }
  667. }
  668. )
  669. }
  670. private func sanitizeIndex(_ index: Int) -> Int {
  671. let newIndex = index % numMediaItems
  672. if newIndex < 0 {
  673. return newIndex + numMediaItems
  674. }
  675. return newIndex
  676. }
  677. private func sourceImage() -> UIImage? {
  678. return mediaView(at: 1)?.image
  679. }
  680. private func mediaView(at index: Int) -> MediaContentView? {
  681. guard index < contentViews.count else {
  682. assertionFailure("Content views does not have this many views. : \(index)")
  683. return nil
  684. }
  685. return contentViews[index]
  686. }
  687. }
  688. // MARK: - UIGestureRecognizerDelegate
  689. extension MediaBrowserViewController: UIGestureRecognizerDelegate {
  690. public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  691. guard enableInteractiveDismissal else {
  692. return true
  693. }
  694. let middleView = mediaView(at: 1)
  695. if middleView?.zoomScale == middleView?.zoomLevels?.minimumZoomScale,
  696. let recognizer = gestureRecognizer as? UIPanGestureRecognizer {
  697. let translation = recognizer.translation(in: recognizer.view)
  698. if gestureDirection == .horizontal {
  699. dismissController.interactionInProgress = abs(translation.y) > abs(translation.x)
  700. } else {
  701. dismissController.interactionInProgress = abs(translation.x) > abs(translation.y)
  702. }
  703. if dismissController.interactionInProgress {
  704. dismissController.image = sourceImage()
  705. }
  706. }
  707. return true
  708. }
  709. public func gestureRecognizer(
  710. _ gestureRecognizer: UIGestureRecognizer,
  711. shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
  712. ) -> Bool {
  713. if gestureRecognizer is UIPanGestureRecognizer,
  714. let scrollView = otherGestureRecognizer.view as? MediaContentView {
  715. return scrollView.zoomScale == 1.0
  716. }
  717. return false
  718. }
  719. public func gestureRecognizer(
  720. _ gestureRecognizer: UIGestureRecognizer,
  721. shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer
  722. ) -> Bool {
  723. if gestureRecognizer is UITapGestureRecognizer {
  724. return otherGestureRecognizer.view is MediaContentView
  725. }
  726. return false
  727. }
  728. }