MediaBrowserViewController.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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, view: MediaContentView)
  71. func mediaBrowserTap(_ view: MediaContentView)
  72. func mediaBrowserDismiss()
  73. }
  74. extension MediaBrowserViewControllerDelegate {
  75. public func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, didChangeFocusTo index: Int, view: MediaContentView) {}
  76. }
  77. public class MediaBrowserViewController: UIViewController {
  78. // MARK: - Exposed Enumerations
  79. /**
  80. Enum to hold supported gesture directions.
  81. ```
  82. case horizontal
  83. case vertical
  84. ```
  85. */
  86. public enum GestureDirection {
  87. /// Horizontal (left - right) gestures.
  88. case horizontal
  89. /// Vertical (up - down) gestures.
  90. case vertical
  91. }
  92. /**
  93. Enum to hold supported browser styles.
  94. ```
  95. case linear
  96. case carousel
  97. ```
  98. */
  99. public enum BrowserStyle {
  100. /// Linear browser with *0* as first index and *numItems-1* as last index.
  101. case linear
  102. /// Carousel browser. The media items are repeated in a circular fashion.
  103. case carousel
  104. }
  105. /**
  106. Enum to hold supported content draw orders.
  107. ```
  108. case previousToNext
  109. case nextToPrevious
  110. ```
  111. - note:
  112. Remember that this is draw order, not positioning. This order decides which item will
  113. be above or below other items, when they overlap.
  114. */
  115. public enum ContentDrawOrder {
  116. /// In this mode, media items are rendered in [previous]-[current]-[next] order.
  117. case previousToNext
  118. /// In this mode, media items are rendered in [next]-[current]-[previous] order.
  119. case nextToPrevious
  120. }
  121. // MARK: - Exposed variables
  122. /// Data-source object to supply media browser contents.
  123. public weak var dataSource: MediaBrowserViewControllerDataSource?
  124. /// Delegate object to get callbacks on media browser events.
  125. public weak var delegate: MediaBrowserViewControllerDelegate?
  126. /// Gesture direction. Default is `horizontal`.
  127. public var gestureDirection: GestureDirection = .horizontal
  128. /// Content transformer closure. Default is `horizontalMoveInOut`.
  129. public var contentTransformer: ContentTransformer = DefaultContentTransformers.horizontalMoveInOut {
  130. didSet {
  131. MediaContentView.contentTransformer = contentTransformer
  132. contentViews.forEach({ $0.updateTransform() })
  133. }
  134. }
  135. /// Content draw order. Default is `previousToNext`.
  136. public var drawOrder: ContentDrawOrder = .previousToNext {
  137. didSet {
  138. if oldValue != drawOrder {
  139. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  140. }
  141. }
  142. }
  143. /// Browser style. Default is carousel.
  144. public var browserStyle: BrowserStyle = .carousel
  145. /// Gap between consecutive media items. Default is `50.0`.
  146. public var gapBetweenMediaViews: CGFloat = Constants.gapBetweenContents {
  147. didSet {
  148. MediaContentView.interItemSpacing = gapBetweenMediaViews
  149. contentViews.forEach({ $0.updateTransform() })
  150. }
  151. }
  152. /// Enable or disable interactive dismissal. Default is enabled.
  153. public var enableInteractiveDismissal: Bool = true
  154. /// Item index of the current item. In range `0..<numMediaItems`
  155. public var currentItemIndex: Int {
  156. return sanitizeIndex(index)
  157. }
  158. // MARK: - Private Enumerations
  159. private enum Constants {
  160. static let gapBetweenContents: CGFloat = 50.0
  161. static let minimumVelocity: CGFloat = 15.0
  162. static let minimumTranslation: CGFloat = 0.1
  163. static let animationDuration = 0.3
  164. static let updateFrameRate: CGFloat = 60.0
  165. static let bounceFactor: CGFloat = 0.1
  166. enum PageControl {
  167. static let bottom: CGFloat = -10.0
  168. static let tintColor: UIColor = .lightGray
  169. static let selectedTintColor: UIColor = .white
  170. }
  171. }
  172. // MARK: - Private variables
  173. private(set) var index: Int = 0 {
  174. didSet {
  175. pageControl.currentPage = index
  176. }
  177. }
  178. public var contentViews: [MediaContentView] = []
  179. private var previousTranslation: CGPoint = .zero
  180. private var timer: Timer?
  181. private var distanceToMove: CGFloat = 0.0
  182. lazy private var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
  183. let gesture = UIPanGestureRecognizer()
  184. gesture.minimumNumberOfTouches = 1
  185. gesture.maximumNumberOfTouches = 1
  186. gesture.delegate = self
  187. gesture.addTarget(self, action: #selector(panGestureEvent(_:)))
  188. return gesture
  189. }()
  190. lazy internal private(set) var mediaContainerView: UIView = { [unowned self] in
  191. let container = UIView()
  192. container.backgroundColor = .clear
  193. return container
  194. }()
  195. lazy private var pageControl: UIPageControl = { [unowned self] in
  196. let pageControl = UIPageControl()
  197. pageControl.hidesForSinglePage = true
  198. pageControl.numberOfPages = numMediaItems
  199. pageControl.currentPageIndicatorTintColor = Constants.PageControl.selectedTintColor
  200. pageControl.tintColor = Constants.PageControl.tintColor
  201. pageControl.currentPage = index
  202. return pageControl
  203. }()
  204. private var numMediaItems = 0
  205. private lazy var dismissController = DismissAnimationController(
  206. gestureDirection: gestureDirection,
  207. viewController: self
  208. )
  209. // MARK: - Public methods
  210. /// Invoking this method reloads the contents media browser.
  211. public func reloadContentViews() {
  212. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  213. for contentView in contentViews {
  214. updateContents(of: contentView)
  215. }
  216. }
  217. // MARK: - Initializers
  218. public init(
  219. index: Int = 0,
  220. dataSource: MediaBrowserViewControllerDataSource,
  221. delegate: MediaBrowserViewControllerDelegate? = nil
  222. ) {
  223. self.index = index
  224. self.dataSource = dataSource
  225. self.delegate = delegate
  226. super.init(nibName: nil, bundle: nil)
  227. initialize()
  228. }
  229. public required init?(coder aDecoder: NSCoder) {
  230. super.init(coder: aDecoder)
  231. initialize()
  232. }
  233. private func initialize() {
  234. view.backgroundColor = .clear
  235. modalPresentationStyle = .custom
  236. modalTransitionStyle = .crossDissolve
  237. }
  238. public func changeInViewSize(to size: CGSize) {
  239. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  240. }
  241. }
  242. // MARK: - View Lifecycle and Events
  243. extension MediaBrowserViewController {
  244. override public var prefersStatusBarHidden: Bool {
  245. return true
  246. }
  247. override public func viewDidLoad() {
  248. super.viewDidLoad()
  249. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  250. populateContentViews()
  251. view.addGestureRecognizer(panGestureRecognizer)
  252. }
  253. override public func viewDidAppear(_ animated: Bool) {
  254. super.viewDidAppear(animated)
  255. contentViews.forEach({ $0.updateTransform() })
  256. }
  257. override public func viewWillDisappear(_ animated: Bool) {
  258. super.viewWillDisappear(animated)
  259. }
  260. public override func viewWillTransition(
  261. to size: CGSize,
  262. with coordinator: UIViewControllerTransitionCoordinator
  263. ) {
  264. coordinator.animate(alongsideTransition: { context in
  265. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  266. }, completion: nil)
  267. super.viewWillTransition(to: size, with: coordinator)
  268. }
  269. private func populateContentViews() {
  270. view.addSubview(mediaContainerView)
  271. mediaContainerView.translatesAutoresizingMaskIntoConstraints = false
  272. NSLayoutConstraint.activate([
  273. mediaContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  274. mediaContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  275. mediaContainerView.topAnchor.constraint(equalTo: view.topAnchor),
  276. mediaContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  277. ])
  278. MediaContentView.interItemSpacing = gapBetweenMediaViews
  279. MediaContentView.contentTransformer = contentTransformer
  280. contentViews.forEach({ $0.removeFromSuperview() })
  281. contentViews.removeAll()
  282. for i in -1...1 {
  283. let mediaView = MediaContentView(
  284. index: i + index,
  285. position: CGFloat(i),
  286. frame: view.bounds,
  287. delegate: self.delegate
  288. )
  289. mediaContainerView.addSubview(mediaView)
  290. mediaView.translatesAutoresizingMaskIntoConstraints = false
  291. NSLayoutConstraint.activate([
  292. mediaView.leadingAnchor.constraint(equalTo: mediaContainerView.leadingAnchor),
  293. mediaView.trailingAnchor.constraint(equalTo: mediaContainerView.trailingAnchor),
  294. mediaView.topAnchor.constraint(equalTo: mediaContainerView.topAnchor),
  295. mediaView.bottomAnchor.constraint(equalTo: mediaContainerView.bottomAnchor)
  296. ])
  297. contentViews.append(mediaView)
  298. if numMediaItems > 0 {
  299. updateContents(of: mediaView)
  300. }
  301. }
  302. if drawOrder == .nextToPrevious {
  303. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  304. }
  305. }
  306. }
  307. // MARK: - Gesture Recognizers
  308. extension MediaBrowserViewController {
  309. @objc private func panGestureEvent(_ recognizer: UIPanGestureRecognizer) {
  310. if dismissController.interactionInProgress {
  311. dismissController.handleInteractiveTransition(recognizer)
  312. return
  313. }
  314. guard numMediaItems > 0 else {
  315. return
  316. }
  317. let translation = recognizer.translation(in: view)
  318. switch recognizer.state {
  319. case .began:
  320. previousTranslation = translation
  321. distanceToMove = 0.0
  322. timer?.invalidate()
  323. timer = nil
  324. case .changed:
  325. moveViews(by: CGPoint(x: translation.x - previousTranslation.x, y: translation.y - previousTranslation.y))
  326. case .ended, .failed, .cancelled:
  327. let velocity = recognizer.velocity(in: view)
  328. var viewsCopy = contentViews
  329. let previousView = viewsCopy.removeFirst()
  330. let middleView = viewsCopy.removeFirst()
  331. let nextView = viewsCopy.removeFirst()
  332. var toMove: CGFloat = 0.0
  333. let directionalVelocity = gestureDirection == .horizontal ? velocity.x : velocity.y
  334. if abs(directionalVelocity) < Constants.minimumVelocity &&
  335. abs(middleView.position) < Constants.minimumTranslation {
  336. toMove = -middleView.position
  337. } else if directionalVelocity < 0.0 {
  338. if middleView.position >= 0.0 {
  339. toMove = -middleView.position
  340. } else {
  341. toMove = -nextView.position
  342. }
  343. } else {
  344. if middleView.position <= 0.0 {
  345. toMove = -middleView.position
  346. } else {
  347. toMove = -previousView.position
  348. }
  349. }
  350. if browserStyle == .linear || numMediaItems <= 1 {
  351. if (middleView.index == 0 && ((middleView.position + toMove) > 0.0)) ||
  352. (middleView.index == (numMediaItems - 1) && (middleView.position + toMove) < 0.0) {
  353. toMove = -middleView.position
  354. }
  355. }
  356. distanceToMove = toMove
  357. if timer == nil {
  358. timer = Timer.scheduledTimer(
  359. timeInterval: 1.0/Double(Constants.updateFrameRate),
  360. target: self,
  361. selector: #selector(update(_:)),
  362. userInfo: nil,
  363. repeats: true
  364. )
  365. }
  366. default:
  367. break
  368. }
  369. previousTranslation = translation
  370. }
  371. }
  372. // MARK: - Updating View Positions
  373. extension MediaBrowserViewController {
  374. @objc private func update(_ timeInterval: TimeInterval) {
  375. guard distanceToMove != 0.0 else {
  376. timer?.invalidate()
  377. timer = nil
  378. return
  379. }
  380. let distance = distanceToMove / (Constants.updateFrameRate * 0.1)
  381. distanceToMove -= distance
  382. moveViewsNormalized(by: CGPoint(x: distance, y: distance))
  383. let translation = CGPoint(
  384. x: distance * (view.frame.size.width + gapBetweenMediaViews),
  385. y: distance * (view.frame.size.height + gapBetweenMediaViews)
  386. )
  387. let directionalTranslation = (gestureDirection == .horizontal) ? translation.x : translation.y
  388. if abs(directionalTranslation) < 0.1 {
  389. moveViewsNormalized(by: CGPoint(x: distanceToMove, y: distanceToMove))
  390. distanceToMove = 0.0
  391. timer?.invalidate()
  392. timer = nil
  393. }
  394. }
  395. private func moveViews(by translation: CGPoint) {
  396. let viewSizeIncludingGap = CGSize(
  397. width: view.frame.size.width + gapBetweenMediaViews,
  398. height: view.frame.size.height + gapBetweenMediaViews
  399. )
  400. let normalizedTranslation = calculateNormalizedTranslation(
  401. translation: translation,
  402. viewSize: viewSizeIncludingGap
  403. )
  404. moveViewsNormalized(by: normalizedTranslation)
  405. }
  406. private func moveViewsNormalized(by normalizedTranslation: CGPoint) {
  407. let isGestureHorizontal = (gestureDirection == .horizontal)
  408. contentViews.forEach({
  409. $0.position += isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  410. })
  411. var viewsCopy = contentViews
  412. let previousView = viewsCopy.removeFirst()
  413. let middleView = viewsCopy.removeFirst()
  414. let nextView = viewsCopy.removeFirst()
  415. let viewSizeIncludingGap = CGSize(
  416. width: view.frame.size.width + gapBetweenMediaViews,
  417. height: view.frame.size.height + gapBetweenMediaViews
  418. )
  419. let viewSize = isGestureHorizontal ? viewSizeIncludingGap.width : viewSizeIncludingGap.height
  420. let normalizedGap = gapBetweenMediaViews/viewSize
  421. let normalizedCenter = (middleView.frame.size.width / viewSize) * 0.5
  422. let viewCount = contentViews.count
  423. if middleView.position < -(normalizedGap + normalizedCenter) {
  424. index = sanitizeIndex(index + 1)
  425. // Previous item is taken and placed on right/down most side
  426. previousView.position += CGFloat(viewCount)
  427. previousView.index += viewCount
  428. updateContents(of: previousView)
  429. contentViews.removeFirst()
  430. contentViews.append(previousView)
  431. switch drawOrder {
  432. case .previousToNext:
  433. mediaContainerView.bringSubviewToFront(previousView)
  434. case .nextToPrevious:
  435. mediaContainerView.sendSubviewToBack(previousView)
  436. }
  437. delegate?.mediaBrowser(self, didChangeFocusTo: index, view: nextView)
  438. } else if middleView.position > (1 + normalizedGap - normalizedCenter) {
  439. index = sanitizeIndex(index - 1)
  440. // Next item is taken and placed on left/top most side
  441. nextView.position -= CGFloat(viewCount)
  442. nextView.index -= viewCount
  443. updateContents(of: nextView)
  444. contentViews.removeLast()
  445. contentViews.insert(nextView, at: 0)
  446. switch drawOrder {
  447. case .previousToNext:
  448. mediaContainerView.sendSubviewToBack(nextView)
  449. case .nextToPrevious:
  450. mediaContainerView.bringSubviewToFront(nextView)
  451. }
  452. delegate?.mediaBrowser(self, didChangeFocusTo: index, view: previousView)
  453. }
  454. }
  455. private func calculateNormalizedTranslation(translation: CGPoint, viewSize: CGSize) -> CGPoint {
  456. guard let middleView = mediaView(at: 1) else {
  457. return .zero
  458. }
  459. var normalizedTranslation = CGPoint(
  460. x: (translation.x)/viewSize.width,
  461. y: (translation.y)/viewSize.height
  462. )
  463. if browserStyle != .carousel || numMediaItems <= 1 {
  464. let isGestureHorizontal = (gestureDirection == .horizontal)
  465. let directionalTranslation = isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  466. if (middleView.index == 0 && ((middleView.position + directionalTranslation) > 0.0)) ||
  467. (middleView.index == (numMediaItems - 1) && (middleView.position + directionalTranslation) < 0.0) {
  468. if isGestureHorizontal {
  469. normalizedTranslation.x *= Constants.bounceFactor
  470. } else {
  471. normalizedTranslation.y *= Constants.bounceFactor
  472. }
  473. }
  474. }
  475. return normalizedTranslation
  476. }
  477. private func updateContents(of contentView: MediaContentView) {
  478. contentView.image = nil
  479. let convertedIndex = sanitizeIndex(contentView.index)
  480. contentView.isLoading = true
  481. dataSource?.mediaBrowser(
  482. self,
  483. imageAt: convertedIndex,
  484. completion: { [weak self] (index, image, zoom, _) in
  485. guard let strongSelf = self else {
  486. return
  487. }
  488. if index == strongSelf.sanitizeIndex(contentView.index) {
  489. if image != nil {
  490. contentView.image = image
  491. contentView.zoomLevels = zoom
  492. }
  493. contentView.isLoading = false
  494. }
  495. }
  496. )
  497. }
  498. private func sanitizeIndex(_ index: Int) -> Int {
  499. let newIndex = index % numMediaItems
  500. if newIndex < 0 {
  501. return newIndex + numMediaItems
  502. }
  503. return newIndex
  504. }
  505. private func sourceImage() -> UIImage? {
  506. return mediaView(at: 1)?.image
  507. }
  508. private func mediaView(at index: Int) -> MediaContentView? {
  509. guard index < contentViews.count else {
  510. assertionFailure("Content views does not have this many views. : \(index)")
  511. return nil
  512. }
  513. return contentViews[index]
  514. }
  515. }
  516. // MARK: - UIGestureRecognizerDelegate
  517. extension MediaBrowserViewController: UIGestureRecognizerDelegate {
  518. public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  519. guard enableInteractiveDismissal else {
  520. return true
  521. }
  522. let middleView = mediaView(at: 1)
  523. if middleView?.zoomScale == middleView?.zoomLevels?.minimumZoomScale,
  524. let recognizer = gestureRecognizer as? UIPanGestureRecognizer {
  525. let translation = recognizer.translation(in: recognizer.view)
  526. if gestureDirection == .horizontal {
  527. dismissController.interactionInProgress = abs(translation.y) > abs(translation.x)
  528. } else {
  529. dismissController.interactionInProgress = abs(translation.x) > abs(translation.y)
  530. }
  531. if dismissController.interactionInProgress {
  532. dismissController.image = sourceImage()
  533. }
  534. }
  535. return true
  536. }
  537. public func gestureRecognizer(
  538. _ gestureRecognizer: UIGestureRecognizer,
  539. shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
  540. ) -> Bool {
  541. if gestureRecognizer is UIPanGestureRecognizer,
  542. let scrollView = otherGestureRecognizer.view as? MediaContentView {
  543. return scrollView.zoomScale == 1.0
  544. }
  545. return false
  546. }
  547. public func gestureRecognizer(
  548. _ gestureRecognizer: UIGestureRecognizer,
  549. shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer
  550. ) -> Bool {
  551. if gestureRecognizer is UITapGestureRecognizer {
  552. return otherGestureRecognizer.view is MediaContentView
  553. }
  554. return false
  555. }
  556. }