MediaBrowserViewController.swift 29 KB

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