MediaBrowserViewController.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 mediaBrowserTap(_ mediaBrowser: MediaBrowserViewController)
  72. func mediaBrowserDismiss()
  73. }
  74. extension MediaBrowserViewControllerDelegate {
  75. public func mediaBrowser(_ mediaBrowser: MediaBrowserViewController, didChangeFocusTo index: Int) {}
  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. private var contentViews: [MediaContentView] = []
  179. lazy private var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
  180. let gesture = UITapGestureRecognizer()
  181. gesture.numberOfTapsRequired = 1
  182. gesture.numberOfTouchesRequired = 1
  183. gesture.delegate = self
  184. gesture.addTarget(self, action: #selector(tapGestureEvent(_:)))
  185. return gesture
  186. }()
  187. private var previousTranslation: CGPoint = .zero
  188. private var timer: Timer?
  189. private var distanceToMove: CGFloat = 0.0
  190. lazy private var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
  191. let gesture = UIPanGestureRecognizer()
  192. gesture.minimumNumberOfTouches = 1
  193. gesture.maximumNumberOfTouches = 1
  194. gesture.delegate = self
  195. gesture.addTarget(self, action: #selector(panGestureEvent(_:)))
  196. return gesture
  197. }()
  198. lazy internal private(set) var mediaContainerView: UIView = { [unowned self] in
  199. let container = UIView()
  200. container.backgroundColor = .clear
  201. return container
  202. }()
  203. lazy private var pageControl: UIPageControl = { [unowned self] in
  204. let pageControl = UIPageControl()
  205. pageControl.hidesForSinglePage = true
  206. pageControl.numberOfPages = numMediaItems
  207. pageControl.currentPageIndicatorTintColor = Constants.PageControl.selectedTintColor
  208. pageControl.tintColor = Constants.PageControl.tintColor
  209. pageControl.currentPage = index
  210. return pageControl
  211. }()
  212. private var numMediaItems = 0
  213. private lazy var dismissController = DismissAnimationController(
  214. gestureDirection: gestureDirection,
  215. viewController: self
  216. )
  217. // MARK: - Public methods
  218. /// Invoking this method reloads the contents media browser.
  219. public func reloadContentViews() {
  220. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  221. for contentView in contentViews {
  222. updateContents(of: contentView)
  223. }
  224. }
  225. // MARK: - Initializers
  226. public init(
  227. index: Int = 0,
  228. dataSource: MediaBrowserViewControllerDataSource,
  229. delegate: MediaBrowserViewControllerDelegate? = nil
  230. ) {
  231. self.index = index
  232. self.dataSource = dataSource
  233. self.delegate = delegate
  234. super.init(nibName: nil, bundle: nil)
  235. initialize()
  236. }
  237. public required init?(coder aDecoder: NSCoder) {
  238. super.init(coder: aDecoder)
  239. initialize()
  240. }
  241. private func initialize() {
  242. view.backgroundColor = .clear
  243. modalPresentationStyle = .custom
  244. modalTransitionStyle = .crossDissolve
  245. }
  246. public func changeInViewSize(to size: CGSize) {
  247. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  248. }
  249. }
  250. // MARK: - View Lifecycle and Events
  251. extension MediaBrowserViewController {
  252. override public var prefersStatusBarHidden: Bool {
  253. return true
  254. }
  255. override public func viewDidLoad() {
  256. super.viewDidLoad()
  257. numMediaItems = dataSource?.numberOfItems(in: self) ?? 0
  258. populateContentViews()
  259. view.addGestureRecognizer(panGestureRecognizer)
  260. view.addGestureRecognizer(tapGestureRecognizer)
  261. }
  262. override public func viewDidAppear(_ animated: Bool) {
  263. super.viewDidAppear(animated)
  264. contentViews.forEach({ $0.updateTransform() })
  265. }
  266. override public func viewWillDisappear(_ animated: Bool) {
  267. super.viewWillDisappear(animated)
  268. }
  269. public override func viewWillTransition(
  270. to size: CGSize,
  271. with coordinator: UIViewControllerTransitionCoordinator
  272. ) {
  273. coordinator.animate(alongsideTransition: { context in
  274. self.contentViews.forEach({ $0.handleChangeInViewSize(to: size) })
  275. }, completion: nil)
  276. super.viewWillTransition(to: size, with: coordinator)
  277. }
  278. private func populateContentViews() {
  279. view.addSubview(mediaContainerView)
  280. mediaContainerView.translatesAutoresizingMaskIntoConstraints = false
  281. NSLayoutConstraint.activate([
  282. mediaContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  283. mediaContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  284. mediaContainerView.topAnchor.constraint(equalTo: view.topAnchor),
  285. mediaContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  286. ])
  287. MediaContentView.interItemSpacing = gapBetweenMediaViews
  288. MediaContentView.contentTransformer = contentTransformer
  289. contentViews.forEach({ $0.removeFromSuperview() })
  290. contentViews.removeAll()
  291. for i in -1...1 {
  292. let mediaView = MediaContentView(
  293. index: i + index,
  294. position: CGFloat(i),
  295. frame: view.bounds
  296. )
  297. mediaContainerView.addSubview(mediaView)
  298. mediaView.translatesAutoresizingMaskIntoConstraints = false
  299. NSLayoutConstraint.activate([
  300. mediaView.leadingAnchor.constraint(equalTo: mediaContainerView.leadingAnchor),
  301. mediaView.trailingAnchor.constraint(equalTo: mediaContainerView.trailingAnchor),
  302. mediaView.topAnchor.constraint(equalTo: mediaContainerView.topAnchor),
  303. mediaView.bottomAnchor.constraint(equalTo: mediaContainerView.bottomAnchor)
  304. ])
  305. contentViews.append(mediaView)
  306. if numMediaItems > 0 {
  307. updateContents(of: mediaView)
  308. }
  309. }
  310. if drawOrder == .nextToPrevious {
  311. mediaContainerView.exchangeSubview(at: 0, withSubviewAt: 2)
  312. }
  313. }
  314. }
  315. // MARK: - Gesture Recognizers
  316. extension MediaBrowserViewController {
  317. @objc private func panGestureEvent(_ recognizer: UIPanGestureRecognizer) {
  318. if dismissController.interactionInProgress {
  319. dismissController.handleInteractiveTransition(recognizer)
  320. return
  321. }
  322. guard numMediaItems > 0 else {
  323. return
  324. }
  325. let translation = recognizer.translation(in: view)
  326. switch recognizer.state {
  327. case .began:
  328. previousTranslation = translation
  329. distanceToMove = 0.0
  330. timer?.invalidate()
  331. timer = nil
  332. case .changed:
  333. moveViews(by: CGPoint(x: translation.x - previousTranslation.x, y: translation.y - previousTranslation.y))
  334. case .ended, .failed, .cancelled:
  335. let velocity = recognizer.velocity(in: view)
  336. var viewsCopy = contentViews
  337. let previousView = viewsCopy.removeFirst()
  338. let middleView = viewsCopy.removeFirst()
  339. let nextView = viewsCopy.removeFirst()
  340. var toMove: CGFloat = 0.0
  341. let directionalVelocity = gestureDirection == .horizontal ? velocity.x : velocity.y
  342. if abs(directionalVelocity) < Constants.minimumVelocity &&
  343. abs(middleView.position) < Constants.minimumTranslation {
  344. toMove = -middleView.position
  345. } else if directionalVelocity < 0.0 {
  346. if middleView.position >= 0.0 {
  347. toMove = -middleView.position
  348. } else {
  349. toMove = -nextView.position
  350. }
  351. } else {
  352. if middleView.position <= 0.0 {
  353. toMove = -middleView.position
  354. } else {
  355. toMove = -previousView.position
  356. }
  357. }
  358. if browserStyle == .linear || numMediaItems <= 1 {
  359. if (middleView.index == 0 && ((middleView.position + toMove) > 0.0)) ||
  360. (middleView.index == (numMediaItems - 1) && (middleView.position + toMove) < 0.0) {
  361. toMove = -middleView.position
  362. }
  363. }
  364. distanceToMove = toMove
  365. if timer == nil {
  366. timer = Timer.scheduledTimer(
  367. timeInterval: 1.0/Double(Constants.updateFrameRate),
  368. target: self,
  369. selector: #selector(update(_:)),
  370. userInfo: nil,
  371. repeats: true
  372. )
  373. }
  374. default:
  375. break
  376. }
  377. previousTranslation = translation
  378. }
  379. @objc private func tapGestureEvent(_ recognizer: UITapGestureRecognizer) {
  380. guard !dismissController.interactionInProgress else {
  381. return
  382. }
  383. self.delegate?.mediaBrowserTap(self)
  384. }
  385. }
  386. // MARK: - Updating View Positions
  387. extension MediaBrowserViewController {
  388. @objc private func update(_ timeInterval: TimeInterval) {
  389. guard distanceToMove != 0.0 else {
  390. timer?.invalidate()
  391. timer = nil
  392. return
  393. }
  394. let distance = distanceToMove / (Constants.updateFrameRate * 0.1)
  395. distanceToMove -= distance
  396. moveViewsNormalized(by: CGPoint(x: distance, y: distance))
  397. let translation = CGPoint(
  398. x: distance * (view.frame.size.width + gapBetweenMediaViews),
  399. y: distance * (view.frame.size.height + gapBetweenMediaViews)
  400. )
  401. let directionalTranslation = (gestureDirection == .horizontal) ? translation.x : translation.y
  402. if abs(directionalTranslation) < 0.1 {
  403. moveViewsNormalized(by: CGPoint(x: distanceToMove, y: distanceToMove))
  404. distanceToMove = 0.0
  405. timer?.invalidate()
  406. timer = nil
  407. }
  408. }
  409. private func moveViews(by translation: CGPoint) {
  410. let viewSizeIncludingGap = CGSize(
  411. width: view.frame.size.width + gapBetweenMediaViews,
  412. height: view.frame.size.height + gapBetweenMediaViews
  413. )
  414. let normalizedTranslation = calculateNormalizedTranslation(
  415. translation: translation,
  416. viewSize: viewSizeIncludingGap
  417. )
  418. moveViewsNormalized(by: normalizedTranslation)
  419. }
  420. private func moveViewsNormalized(by normalizedTranslation: CGPoint) {
  421. let isGestureHorizontal = (gestureDirection == .horizontal)
  422. contentViews.forEach({
  423. $0.position += isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  424. })
  425. var viewsCopy = contentViews
  426. let previousView = viewsCopy.removeFirst()
  427. let middleView = viewsCopy.removeFirst()
  428. let nextView = viewsCopy.removeFirst()
  429. let viewSizeIncludingGap = CGSize(
  430. width: view.frame.size.width + gapBetweenMediaViews,
  431. height: view.frame.size.height + gapBetweenMediaViews
  432. )
  433. let viewSize = isGestureHorizontal ? viewSizeIncludingGap.width : viewSizeIncludingGap.height
  434. let normalizedGap = gapBetweenMediaViews/viewSize
  435. let normalizedCenter = (middleView.frame.size.width / viewSize) * 0.5
  436. let viewCount = contentViews.count
  437. if middleView.position < -(normalizedGap + normalizedCenter) {
  438. index = sanitizeIndex(index + 1)
  439. // Previous item is taken and placed on right/down most side
  440. previousView.position += CGFloat(viewCount)
  441. previousView.index += viewCount
  442. updateContents(of: previousView)
  443. contentViews.removeFirst()
  444. contentViews.append(previousView)
  445. switch drawOrder {
  446. case .previousToNext:
  447. mediaContainerView.bringSubviewToFront(previousView)
  448. case .nextToPrevious:
  449. mediaContainerView.sendSubviewToBack(previousView)
  450. }
  451. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  452. } else if middleView.position > (1 + normalizedGap - normalizedCenter) {
  453. index = sanitizeIndex(index - 1)
  454. // Next item is taken and placed on left/top most side
  455. nextView.position -= CGFloat(viewCount)
  456. nextView.index -= viewCount
  457. updateContents(of: nextView)
  458. contentViews.removeLast()
  459. contentViews.insert(nextView, at: 0)
  460. switch drawOrder {
  461. case .previousToNext:
  462. mediaContainerView.sendSubviewToBack(nextView)
  463. case .nextToPrevious:
  464. mediaContainerView.bringSubviewToFront(nextView)
  465. }
  466. delegate?.mediaBrowser(self, didChangeFocusTo: index)
  467. }
  468. }
  469. private func calculateNormalizedTranslation(translation: CGPoint, viewSize: CGSize) -> CGPoint {
  470. guard let middleView = mediaView(at: 1) else {
  471. return .zero
  472. }
  473. var normalizedTranslation = CGPoint(
  474. x: (translation.x)/viewSize.width,
  475. y: (translation.y)/viewSize.height
  476. )
  477. if browserStyle != .carousel || numMediaItems <= 1 {
  478. let isGestureHorizontal = (gestureDirection == .horizontal)
  479. let directionalTranslation = isGestureHorizontal ? normalizedTranslation.x : normalizedTranslation.y
  480. if (middleView.index == 0 && ((middleView.position + directionalTranslation) > 0.0)) ||
  481. (middleView.index == (numMediaItems - 1) && (middleView.position + directionalTranslation) < 0.0) {
  482. if isGestureHorizontal {
  483. normalizedTranslation.x *= Constants.bounceFactor
  484. } else {
  485. normalizedTranslation.y *= Constants.bounceFactor
  486. }
  487. }
  488. }
  489. return normalizedTranslation
  490. }
  491. private func updateContents(of contentView: MediaContentView) {
  492. contentView.image = nil
  493. let convertedIndex = sanitizeIndex(contentView.index)
  494. contentView.isLoading = true
  495. dataSource?.mediaBrowser(
  496. self,
  497. imageAt: convertedIndex,
  498. completion: { [weak self] (index, image, zoom, _) in
  499. guard let strongSelf = self else {
  500. return
  501. }
  502. if index == strongSelf.sanitizeIndex(contentView.index) {
  503. if image != nil {
  504. contentView.image = image
  505. contentView.zoomLevels = zoom
  506. }
  507. contentView.isLoading = false
  508. }
  509. }
  510. )
  511. }
  512. private func sanitizeIndex(_ index: Int) -> Int {
  513. let newIndex = index % numMediaItems
  514. if newIndex < 0 {
  515. return newIndex + numMediaItems
  516. }
  517. return newIndex
  518. }
  519. private func sourceImage() -> UIImage? {
  520. return mediaView(at: 1)?.image
  521. }
  522. private func mediaView(at index: Int) -> MediaContentView? {
  523. guard index < contentViews.count else {
  524. assertionFailure("Content views does not have this many views. : \(index)")
  525. return nil
  526. }
  527. return contentViews[index]
  528. }
  529. }
  530. // MARK: - UIGestureRecognizerDelegate
  531. extension MediaBrowserViewController: UIGestureRecognizerDelegate {
  532. public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  533. guard enableInteractiveDismissal else {
  534. return true
  535. }
  536. let middleView = mediaView(at: 1)
  537. if middleView?.zoomScale == middleView?.zoomLevels?.minimumZoomScale,
  538. let recognizer = gestureRecognizer as? UIPanGestureRecognizer {
  539. let translation = recognizer.translation(in: recognizer.view)
  540. if gestureDirection == .horizontal {
  541. dismissController.interactionInProgress = abs(translation.y) > abs(translation.x)
  542. } else {
  543. dismissController.interactionInProgress = abs(translation.x) > abs(translation.y)
  544. }
  545. if dismissController.interactionInProgress {
  546. dismissController.image = sourceImage()
  547. }
  548. }
  549. return true
  550. }
  551. public func gestureRecognizer(
  552. _ gestureRecognizer: UIGestureRecognizer,
  553. shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
  554. ) -> Bool {
  555. if gestureRecognizer is UIPanGestureRecognizer,
  556. let scrollView = otherGestureRecognizer.view as? MediaContentView {
  557. return scrollView.zoomScale == 1.0
  558. }
  559. return false
  560. }
  561. public func gestureRecognizer(
  562. _ gestureRecognizer: UIGestureRecognizer,
  563. shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer
  564. ) -> Bool {
  565. if gestureRecognizer is UITapGestureRecognizer {
  566. return otherGestureRecognizer.view is MediaContentView
  567. }
  568. return false
  569. }
  570. }