VLCPagingViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*****************************************************************************
  2. * BaseButtonBarPageTabStripViewController.swift
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2018 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <caro # videolan.org>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. import Foundation
  13. class VLCLabelCell: UICollectionViewCell {
  14. static let cellIdentifier = "VLCLabelCell"
  15. @IBOutlet weak var iconLabel: UILabel!
  16. }
  17. enum SwipeDirection {
  18. case left
  19. case right
  20. case none
  21. }
  22. struct IndicatorInfo {
  23. var title: String?
  24. var accessibilityLabel: String?
  25. init(title: String) {
  26. self.title = title
  27. self.accessibilityLabel = title
  28. }
  29. }
  30. enum PagerScroll {
  31. case no
  32. case yes
  33. case onlyIfOutOfScreen
  34. }
  35. class VLCPagingViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
  36. var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
  37. var buttonBarView: ButtonBarView!
  38. var buttonbarViewHeight: CGFloat = 45.0
  39. lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
  40. return self.calculateWidths()
  41. }()
  42. private var shouldUpdateButtonBarView = true
  43. override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
  44. super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  45. delegate = self
  46. datasource = self
  47. }
  48. @available(*, unavailable, message: "use init(nibName:)")
  49. required init?(coder aDecoder: NSCoder) {
  50. fatalError()
  51. }
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. buttonbarViewHeight = viewControllers.count == 1 ? 0 : 45
  55. let flowLayout = UICollectionViewFlowLayout()
  56. flowLayout.scrollDirection = .horizontal
  57. buttonBarView = ButtonBarView(frame: .zero, collectionViewLayout: flowLayout)
  58. buttonBarView.translatesAutoresizingMaskIntoConstraints = false
  59. view.addSubview(buttonBarView)
  60. NSLayoutConstraint.activate([
  61. buttonBarView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
  62. buttonBarView.rightAnchor.constraint(equalTo: view.rightAnchor),
  63. buttonBarView.leftAnchor.constraint(equalTo: view.leftAnchor),
  64. buttonBarView.heightAnchor.constraint(equalToConstant: buttonbarViewHeight)
  65. ])
  66. //make sure that top and bottom are not covered by tabbar and navigationbar
  67. let bottomGuide: NSLayoutConstraint
  68. if #available(iOS 11.0, *) {
  69. bottomGuide = containerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
  70. } else {
  71. bottomGuide = containerView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
  72. }
  73. NSLayoutConstraint.activate([
  74. containerView.topAnchor.constraint(equalTo: buttonBarView.bottomAnchor),
  75. containerView.rightAnchor.constraint(equalTo: view.rightAnchor),
  76. containerView.leftAnchor.constraint(equalTo: view.leftAnchor),
  77. bottomGuide
  78. ]
  79. )
  80. buttonBarView.delegate = self
  81. buttonBarView.dataSource = self
  82. }
  83. override func viewWillAppear(_ animated: Bool) {
  84. super.viewWillAppear(animated)
  85. buttonBarView.layoutIfNeeded()
  86. isViewAppearing = true
  87. }
  88. override func viewDidAppear(_ animated: Bool) {
  89. super.viewDidAppear(animated)
  90. isViewAppearing = false
  91. }
  92. override func viewDidLayoutSubviews() {
  93. super.viewDidLayoutSubviews()
  94. guard isViewAppearing || isViewRotating else { return }
  95. // Force the UICollectionViewFlowLayout to get laid out again with the new size if
  96. // a) The view is appearing. This ensures that
  97. // collectionView:layout:sizeForItemAtIndexPath: is called for a second time
  98. // when the view is shown and when the view *frame(s)* are actually set
  99. // (we need the view frame's to have been set to work out the size's and on the
  100. // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
  101. // aren't set correctly)
  102. // b) The view is rotating. This ensures that
  103. // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
  104. // *new* frame so that the buttonBarView cell's actually get resized correctly
  105. cachedCellWidths = calculateWidths()
  106. buttonBarView.collectionViewLayout.invalidateLayout()
  107. // When the view first appears or is rotated we also need to ensure that the barButtonView's
  108. // selectedBar is resized and its contentOffset/scroll is set correctly (the selected
  109. // tab/cell may end up either skewed or off screen after a rotation otherwise)
  110. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .onlyIfOutOfScreen)
  111. buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
  112. }
  113. // MARK: - Methods
  114. override func reloadPagerTabStripView() {
  115. super.reloadPagerTabStripView()
  116. guard isViewLoaded else { return }
  117. buttonBarView.reloadData()
  118. cachedCellWidths = calculateWidths()
  119. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
  120. }
  121. func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
  122. var numberOfLargeCells = 0
  123. var totalWidthOfLargeCells: CGFloat = 0
  124. for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
  125. totalWidthOfLargeCells += minimumCellWidthValue
  126. numberOfLargeCells += 1
  127. }
  128. guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
  129. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  130. let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  131. let numberOfCells = minimumCellWidths.count
  132. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  133. let numberOfSmallCells = numberOfCells - numberOfLargeCells
  134. let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
  135. return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
  136. }
  137. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
  138. guard shouldUpdateButtonBarView else { return }
  139. buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
  140. }
  141. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
  142. guard shouldUpdateButtonBarView else { return }
  143. buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
  144. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  145. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
  146. let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  147. changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
  148. }
  149. }
  150. // MARK: - UICollectionViewDelegateFlowLayut
  151. @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
  152. guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
  153. fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
  154. }
  155. return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
  156. }
  157. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  158. guard indexPath.item != currentIndex && containerView.isScrollEnabled else { return }
  159. buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
  160. shouldUpdateButtonBarView = false
  161. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  162. let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
  163. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  164. changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
  165. }
  166. moveToViewController(at: indexPath.item)
  167. }
  168. // MARK: - UICollectionViewDataSource
  169. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  170. return viewControllers.count
  171. }
  172. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  173. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VLCLabelCell.cellIdentifier, for: indexPath) as? ButtonBarCellType else {
  174. fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
  175. }
  176. let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
  177. let indicatorInfo = childController.indicatorInfo(for: self)
  178. configure(cell: cell, for: indicatorInfo)
  179. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  180. changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
  181. }
  182. return cell
  183. }
  184. // MARK: - UIScrollViewDelegate
  185. override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  186. super.scrollViewDidEndScrollingAnimation(scrollView)
  187. guard scrollView == containerView else { return }
  188. shouldUpdateButtonBarView = true
  189. }
  190. func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
  191. fatalError("You must override this method to set up ButtonBarView cell accordingly")
  192. }
  193. private func calculateWidths() -> [CGFloat] {
  194. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  195. let numberOfCells = viewControllers.count
  196. var minimumCellWidths = [CGFloat]()
  197. var collectionViewContentWidth: CGFloat = 0
  198. let indicatorWidth: CGFloat = 70.0
  199. viewControllers.forEach { _ in
  200. minimumCellWidths.append(indicatorWidth)
  201. collectionViewContentWidth += indicatorWidth
  202. }
  203. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  204. collectionViewContentWidth += cellSpacingTotal
  205. let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  206. if collectionViewAvailableVisibleWidth < collectionViewContentWidth {
  207. return minimumCellWidths
  208. } else {
  209. let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
  210. let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
  211. var stretchedCellWidths = [CGFloat]()
  212. for minimumCellWidthValue in minimumCellWidths {
  213. let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
  214. stretchedCellWidths.append(cellWidth)
  215. }
  216. return stretchedCellWidths
  217. }
  218. }
  219. }
  220. // MARK: Protocols
  221. protocol IndicatorInfoProvider {
  222. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
  223. }
  224. protocol PagerTabStripIsProgressiveDelegate: class {
  225. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
  226. }
  227. protocol PagerTabStripDataSource: class {
  228. func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
  229. }